From 37a442902487f510810a64caad4e8b202993a6c6 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 21 Nov 2021 14:28:37 +0800 Subject: [PATCH 01/61] various enhancements to PSRSAEncryptionProvider (#10914) --- .../powershell/rsa_provider.mustache | 135 ++++++++++++++---- .../Private/PSRSAEncryptionProvider.cs | 126 ++++++++++++---- 2 files changed, 209 insertions(+), 52 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/powershell/rsa_provider.mustache b/modules/openapi-generator/src/main/resources/powershell/rsa_provider.mustache index ab9be24df97..c684ce6c3fe 100644 --- a/modules/openapi-generator/src/main/resources/powershell/rsa_provider.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/rsa_provider.mustache @@ -1,3 +1,20 @@ +/* + {{#appName}} + * {{{.}}} + * + {{/appName}} + {{#appDescription}} + * {{{.}}} + * + {{/appDescription}} + {{#version}} + * The version of the OpenAPI document: {{{.}}} + {{/version}} + {{#infoEmail}} + * Contact: {{{.}}} + {{/infoEmail}} + * Generated by: https://github.com/openapitools/openapi-generator.git + */ using System; using System.Collections.Generic; using System.IO; @@ -9,8 +26,17 @@ using System.Text; namespace RSAEncryption { + /// + /// A RSA enccryption provider. + /// public class RSAEncryptionProvider { + /// + /// Get the RSA provider from the PEM file. + /// + /// PEM file. + /// Key pass phrase. + /// Get an instance of RSACryptoServiceProvider. public static RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile,SecureString keyPassPhrase = null) { const String pempubheader = "-----BEGIN PUBLIC KEY-----"; @@ -41,6 +67,12 @@ namespace RSAEncryption return null ; } + /// + /// Convert the private key to bytes. + /// + /// Private key. + /// Key pass phrase. + /// The private key in the form of bytes. static byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPhrase = null) { const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; @@ -69,16 +101,24 @@ namespace RSAEncryption //-------- read PEM encryption info. lines and extract salt ----- if (!str.ReadLine().StartsWith("Proc-Type: 4,ENCRYPTED")) + { return null; + } String saltline = str.ReadLine(); if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) + { return null; + } String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) + { salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); - if (!(str.ReadLine() == "")) + } + if (str.ReadLine() != "") + { return null; + } //------ remaining b64 data is encrypted RSA key ---- String encryptedstr = str.ReadToEnd(); @@ -94,7 +134,9 @@ namespace RSAEncryption byte[] deskey = GetEncryptedKey(salt, keyPassPhrase, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes if (deskey == null) + { return null; + } //------ Decrypt the encrypted 3des-encrypted RSA private key ------ byte[] rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV @@ -102,9 +144,14 @@ namespace RSAEncryption } } + /// + /// Decode the RSA private key. + /// + /// Private key. + /// An instance of RSACryptoServiceProvider. public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + byte[] bytesModules, bytesE, bytesD, bytesP, bytesQ, bytesDp, bytesDq, bytesIq; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); @@ -116,63 +163,76 @@ namespace RSAEncryption { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + { binr.ReadByte(); //advance 1 byte + } else if (twobytes == 0x8230) + { binr.ReadInt16(); //advance 2 bytes + } else + { return null; + } twobytes = binr.ReadUInt16(); if (twobytes != 0x0102) //version number + { return null; + } bt = binr.ReadByte(); if (bt != 0x00) + { return null; + } //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); + bytesModules = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); + bytesE = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); + bytesD = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); + bytesP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); + bytesQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); + bytesDp = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); + bytesDq = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); + bytesIq = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- - RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); - RSAparams.Modulus = MODULUS; - RSAparams.Exponent = E; - RSAparams.D = D; - RSAparams.P = P; - RSAparams.Q = Q; - RSAparams.DP = DP; - RSAparams.DQ = DQ; - RSAparams.InverseQ = IQ; - RSA.ImportParameters(RSAparams); - return RSA; + RSAparams.Modulus = bytesModules; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDp; + RSAparams.DQ = bytesDq; + RSAparams.InverseQ = bytesIq; + rsa.ImportParameters(RSAparams); + return rsa; } catch (Exception) { return null; } - finally { binr.Close(); } + finally + { + binr.Close(); + } } private static int GetIntegerSize(BinaryReader binr) @@ -183,13 +243,16 @@ namespace RSAEncryption int count = 0; bt = binr.ReadByte(); if (bt != 0x02) //expect integer + { return 0; + } bt = binr.ReadByte(); if (bt == 0x81) + { count = binr.ReadByte(); // data size in next byte - else - if (bt == 0x82) + } + else if (bt == 0x82) { highbyte = binr.ReadByte(); // data size in next 2 bytes lowbyte = binr.ReadByte(); @@ -209,10 +272,18 @@ namespace RSAEncryption return count; } + /// + /// Get the encrypted key. + /// + /// Random bytes to be added. + /// Password. + /// Count. + /// Miter. + /// Decrypted key. static byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) { IntPtr unmanagedPswd = IntPtr.Zero; - int HASHLENGTH = 16; //MD5 bytes + const int HASHLENGTH = 16; //MD5 bytes byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results byte[] psbytes = new byte[secpswd.Length]; @@ -234,7 +305,9 @@ namespace RSAEncryption { // ---- Now hash consecutively for count times ------ if (j == 0) + { result = data00; //initialize + } else { Array.Copy(result, hashtarget, result.Length); @@ -243,7 +316,9 @@ namespace RSAEncryption } for (int i = 0; i < count; i++) + { result = md5.ComputeHash(result); + } Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial } byte[] deskey = new byte[24]; @@ -257,6 +332,13 @@ namespace RSAEncryption return deskey; } + /// + /// Decrypt the key. + /// + /// Cipher data. + /// Key to decrypt. + /// Initialization vector. + /// Decrypted key. static byte[] DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) { MemoryStream memst = new MemoryStream(); @@ -269,7 +351,8 @@ namespace RSAEncryption cs.Write(cipherData, 0, cipherData.Length); cs.Close(); } - catch (Exception){ + catch (Exception) + { return null; } byte[] decryptedData = memst.ToArray(); diff --git a/samples/client/petstore/powershell/src/PSPetstore/Private/PSRSAEncryptionProvider.cs b/samples/client/petstore/powershell/src/PSPetstore/Private/PSRSAEncryptionProvider.cs index ab9be24df97..27f40d77172 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Private/PSRSAEncryptionProvider.cs +++ b/samples/client/petstore/powershell/src/PSPetstore/Private/PSRSAEncryptionProvider.cs @@ -1,3 +1,11 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ using System; using System.Collections.Generic; using System.IO; @@ -9,8 +17,17 @@ using System.Text; namespace RSAEncryption { + /// + /// A RSA enccryption provider. + /// public class RSAEncryptionProvider { + /// + /// Get the RSA provider from the PEM file. + /// + /// PEM file. + /// Key pass phrase. + /// Get an instance of RSACryptoServiceProvider. public static RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile,SecureString keyPassPhrase = null) { const String pempubheader = "-----BEGIN PUBLIC KEY-----"; @@ -41,6 +58,12 @@ namespace RSAEncryption return null ; } + /// + /// Convert the private key to bytes. + /// + /// Private key. + /// Key pass phrase. + /// The private key in the form of bytes. static byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPhrase = null) { const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; @@ -69,16 +92,24 @@ namespace RSAEncryption //-------- read PEM encryption info. lines and extract salt ----- if (!str.ReadLine().StartsWith("Proc-Type: 4,ENCRYPTED")) + { return null; + } String saltline = str.ReadLine(); if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) + { return null; + } String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) + { salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); - if (!(str.ReadLine() == "")) + } + if (str.ReadLine() != "") + { return null; + } //------ remaining b64 data is encrypted RSA key ---- String encryptedstr = str.ReadToEnd(); @@ -94,7 +125,9 @@ namespace RSAEncryption byte[] deskey = GetEncryptedKey(salt, keyPassPhrase, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes if (deskey == null) + { return null; + } //------ Decrypt the encrypted 3des-encrypted RSA private key ------ byte[] rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV @@ -102,9 +135,14 @@ namespace RSAEncryption } } + /// + /// Decode the RSA private key. + /// + /// Private key. + /// An instance of RSACryptoServiceProvider. public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + byte[] bytesModules, bytesE, bytesD, bytesP, bytesQ, bytesDp, bytesDq, bytesIq; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); @@ -116,63 +154,76 @@ namespace RSAEncryption { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + { binr.ReadByte(); //advance 1 byte + } else if (twobytes == 0x8230) + { binr.ReadInt16(); //advance 2 bytes + } else + { return null; + } twobytes = binr.ReadUInt16(); if (twobytes != 0x0102) //version number + { return null; + } bt = binr.ReadByte(); if (bt != 0x00) + { return null; + } //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); + bytesModules = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); + bytesE = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); + bytesD = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); + bytesP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); + bytesQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); + bytesDp = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); + bytesDq = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); + bytesIq = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- - RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); - RSAparams.Modulus = MODULUS; - RSAparams.Exponent = E; - RSAparams.D = D; - RSAparams.P = P; - RSAparams.Q = Q; - RSAparams.DP = DP; - RSAparams.DQ = DQ; - RSAparams.InverseQ = IQ; - RSA.ImportParameters(RSAparams); - return RSA; + RSAparams.Modulus = bytesModules; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDp; + RSAparams.DQ = bytesDq; + RSAparams.InverseQ = bytesIq; + rsa.ImportParameters(RSAparams); + return rsa; } catch (Exception) { return null; } - finally { binr.Close(); } + finally + { + binr.Close(); + } } private static int GetIntegerSize(BinaryReader binr) @@ -183,13 +234,16 @@ namespace RSAEncryption int count = 0; bt = binr.ReadByte(); if (bt != 0x02) //expect integer + { return 0; + } bt = binr.ReadByte(); if (bt == 0x81) + { count = binr.ReadByte(); // data size in next byte - else - if (bt == 0x82) + } + else if (bt == 0x82) { highbyte = binr.ReadByte(); // data size in next 2 bytes lowbyte = binr.ReadByte(); @@ -209,10 +263,18 @@ namespace RSAEncryption return count; } + /// + /// Get the encrypted key. + /// + /// Random bytes to be added. + /// Password. + /// Count. + /// Miter. + /// Decrypted key. static byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) { IntPtr unmanagedPswd = IntPtr.Zero; - int HASHLENGTH = 16; //MD5 bytes + const int HASHLENGTH = 16; //MD5 bytes byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results byte[] psbytes = new byte[secpswd.Length]; @@ -234,7 +296,9 @@ namespace RSAEncryption { // ---- Now hash consecutively for count times ------ if (j == 0) + { result = data00; //initialize + } else { Array.Copy(result, hashtarget, result.Length); @@ -243,7 +307,9 @@ namespace RSAEncryption } for (int i = 0; i < count; i++) + { result = md5.ComputeHash(result); + } Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial } byte[] deskey = new byte[24]; @@ -257,6 +323,13 @@ namespace RSAEncryption return deskey; } + /// + /// Decrypt the key. + /// + /// Cipher data. + /// Key to decrypt. + /// Initialization vector. + /// Decrypted key. static byte[] DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) { MemoryStream memst = new MemoryStream(); @@ -269,7 +342,8 @@ namespace RSAEncryption cs.Write(cipherData, 0, cipherData.Length); cs.Close(); } - catch (Exception){ + catch (Exception) + { return null; } byte[] decryptedData = memst.ToArray(); From c244c230531d97ee1fadeabf37ac5ce56c532bb5 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 21 Nov 2021 23:03:25 +0800 Subject: [PATCH 02/61] better null comparison (#10915) --- .../src/main/resources/powershell/api_client.mustache | 6 +++--- .../src/main/resources/powershell/appveyor.mustache | 2 +- .../src/main/resources/powershell/configuration.mustache | 2 +- .../src/main/resources/powershell/model_simple.mustache | 2 +- samples/client/petstore/powershell/appveyor.yml | 2 +- .../powershell/src/PSPetstore/Client/PSConfiguration.ps1 | 2 +- .../client/petstore/powershell/src/PSPetstore/Model/Pet.ps1 | 4 ++-- .../powershell/src/PSPetstore/Private/PSApiClient.ps1 | 6 +++--- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/powershell/api_client.mustache b/modules/openapi-generator/src/main/resources/powershell/api_client.mustache index 2435b7b0ced..f7769247fc4 100644 --- a/modules/openapi-generator/src/main/resources/powershell/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/api_client.mustache @@ -144,7 +144,7 @@ function Invoke-{{{apiNamePrefix}}}ApiClient { {{/hasHttpSignatureMethods}} if ($SkipCertificateCheck -eq $true) { - if ($Configuration["Proxy"] -eq $null) { + if ($null -eq $Configuration["Proxy"]) { # skip certification check, no proxy $Response = Invoke-WebRequest -Uri $UriBuilder.Uri ` -Method $Method ` @@ -166,7 +166,7 @@ function Invoke-{{{apiNamePrefix}}}ApiClient { -ProxyUseDefaultCredentials } } else { - if ($Configuration["Proxy"] -eq $null) { + if ($null -eq $Configuration["Proxy"]) { # perform certification check, no proxy $Response = Invoke-WebRequest -Uri $UriBuilder.Uri ` -Method $Method ` @@ -241,7 +241,7 @@ function DeserializeResponse { [string[]]$ContentTypes ) - If ($ContentTypes -eq $null) { + If ($null -eq $ContentTypes) { $ContentTypes = [string[]]@() } diff --git a/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache b/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache index d1047879e53..1127a6fc20c 100644 --- a/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/appveyor.mustache @@ -20,7 +20,7 @@ test_script: } deploy_script: - pwsh: | - if ($env:APPVEYOR_REPO_TAG -eq $true -and $env:NuGetApiKey -ne $null) { + if ($env:APPVEYOR_REPO_TAG -eq $true -and $null -ne $env:NuGetApiKey) { .\Build.ps1 try { Publish-Module -NuGetApiKey $env:NuGetApiKey -Path .\src\{{{packageName}}}\ -Confirm:$False -Verbose diff --git a/modules/openapi-generator/src/main/resources/powershell/configuration.mustache b/modules/openapi-generator/src/main/resources/powershell/configuration.mustache index 21762dbf5c4..0e674f1f560 100644 --- a/modules/openapi-generator/src/main/resources/powershell/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/configuration.mustache @@ -172,7 +172,7 @@ function Set-{{{apiNamePrefix}}}Configuration { $Script:Configuration['DefaultHeaders'] = $DefaultHeaders } - If ($Proxy -ne $null) { + If ($null -ne $Proxy) { If ($Proxy.GetType().FullName -ne "System.Net.SystemWebProxy" -and $Proxy.GetType().FullName -ne "System.Net.WebRequest+WebProxyWrapperOpaque") { throw "Incorrect Proxy type '$($Proxy.GetType().FullName)'. Must be System.Net.SystemWebProxy or System.Net.WebRequest+WebProxyWrapperOpaque." } diff --git a/modules/openapi-generator/src/main/resources/powershell/model_simple.mustache b/modules/openapi-generator/src/main/resources/powershell/model_simple.mustache index 94f92c3dd03..f7954411df8 100644 --- a/modules/openapi-generator/src/main/resources/powershell/model_simple.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/model_simple.mustache @@ -73,7 +73,7 @@ function Initialize-{{{apiNamePrefix}}}{{{classname}}} { {{#vars}} {{^isNullable}} {{#required}} - if (${{{name}}} -eq $null) { + if ($null -eq ${{{name}}}) { throw "invalid value for '{{{name}}}', '{{{name}}}' cannot be null." } diff --git a/samples/client/petstore/powershell/appveyor.yml b/samples/client/petstore/powershell/appveyor.yml index b6967a7c7b6..86b98d394b5 100644 --- a/samples/client/petstore/powershell/appveyor.yml +++ b/samples/client/petstore/powershell/appveyor.yml @@ -26,7 +26,7 @@ test_script: } deploy_script: - pwsh: | - if ($env:APPVEYOR_REPO_TAG -eq $true -and $env:NuGetApiKey -ne $null) { + if ($env:APPVEYOR_REPO_TAG -eq $true -and $null -ne $env:NuGetApiKey) { .\Build.ps1 try { Publish-Module -NuGetApiKey $env:NuGetApiKey -Path .\src\PSPetstore\ -Confirm:$False -Verbose diff --git a/samples/client/petstore/powershell/src/PSPetstore/Client/PSConfiguration.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Client/PSConfiguration.ps1 index 67e42865831..d24a405660d 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Client/PSConfiguration.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Client/PSConfiguration.ps1 @@ -178,7 +178,7 @@ function Set-PSConfiguration { $Script:Configuration['DefaultHeaders'] = $DefaultHeaders } - If ($Proxy -ne $null) { + If ($null -ne $Proxy) { If ($Proxy.GetType().FullName -ne "System.Net.SystemWebProxy" -and $Proxy.GetType().FullName -ne "System.Net.WebRequest+WebProxyWrapperOpaque") { throw "Incorrect Proxy type '$($Proxy.GetType().FullName)'. Must be System.Net.SystemWebProxy or System.Net.WebRequest+WebProxyWrapperOpaque." } diff --git a/samples/client/petstore/powershell/src/PSPetstore/Model/Pet.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Model/Pet.ps1 index eebc0a22260..5207e6986f6 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Model/Pet.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Model/Pet.ps1 @@ -59,11 +59,11 @@ function Initialize-PSPet { 'Creating PSCustomObject: PSPetstore => PSPet' | Write-Debug $PSBoundParameters | Out-DebugParameter | Write-Debug - if ($Name -eq $null) { + if ($null -eq $Name) { throw "invalid value for 'Name', 'Name' cannot be null." } - if ($PhotoUrls -eq $null) { + if ($null -eq $PhotoUrls) { throw "invalid value for 'PhotoUrls', 'PhotoUrls' cannot be null." } diff --git a/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 index 11745f18614..be338cd33eb 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 @@ -131,7 +131,7 @@ function Invoke-PSApiClient { } if ($SkipCertificateCheck -eq $true) { - if ($Configuration["Proxy"] -eq $null) { + if ($null -eq $Configuration["Proxy"]) { # skip certification check, no proxy $Response = Invoke-WebRequest -Uri $UriBuilder.Uri ` -Method $Method ` @@ -153,7 +153,7 @@ function Invoke-PSApiClient { -ProxyUseDefaultCredentials } } else { - if ($Configuration["Proxy"] -eq $null) { + if ($null -eq $Configuration["Proxy"]) { # perform certification check, no proxy $Response = Invoke-WebRequest -Uri $UriBuilder.Uri ` -Method $Method ` @@ -228,7 +228,7 @@ function DeserializeResponse { [string[]]$ContentTypes ) - If ($ContentTypes -eq $null) { + If ($null -eq $ContentTypes) { $ContentTypes = [string[]]@() } From 6779c33b9de63ae9c7cf0725761e7b0359c9ffb4 Mon Sep 17 00:00:00 2001 From: Ian Cubbon Date: Mon, 22 Nov 2021 01:27:43 -0700 Subject: [PATCH 03/61] [GO][Client] Multipart/form-data Request Support More Than One File (#10843) * Instead of limiting a request to a single file when performing an upload, use a slice of files so an arbitrary number of files can be used in the form. * Remove commented out line of code * Update examples for multi-form file fix for multiple files * Convert spaces to tabs for indentation * Updated examples to have tabs instead of spaces * Add an example of a multipart/form-data OA3 schema that contains two files to be uploaded --- .../src/main/resources/go/api.mustache | 30 +- .../src/main/resources/go/client.mustache | 33 +- .../go/go-petstore/api_another_fake.go | 6 +- .../petstore/go/go-petstore/api_fake.go | 106 ++-- .../go-petstore/api_fake_classname_tags123.go | 6 +- .../client/petstore/go/go-petstore/api_pet.go | 96 ++- .../petstore/go/go-petstore/api_store.go | 24 +- .../petstore/go/go-petstore/api_user.go | 48 +- .../client/petstore/go/go-petstore/client.go | 33 +- .../go-experimental/api_usage.go | 24 +- .../x-auth-id-alias/go-experimental/client.go | 33 +- .../mulitple-data-in-forms/.gitignore | 24 + .../.openapi-generator-ignore | 23 + .../.openapi-generator/FILES | 16 + .../.openapi-generator/VERSION | 1 + .../mulitple-data-in-forms/.travis.yml | 8 + .../features/mulitple-data-in-forms/README.md | 113 ++++ .../mulitple-data-in-forms/api/openapi.yaml | 73 +++ .../mulitple-data-in-forms/api_default.go | 172 ++++++ .../features/mulitple-data-in-forms/client.go | 553 ++++++++++++++++++ .../mulitple-data-in-forms/configuration.go | 230 ++++++++ .../docs/ApiResponse.md | 108 ++++ .../mulitple-data-in-forms/docs/DefaultApi.md | 75 +++ .../mulitple-data-in-forms/git_push.sh | 57 ++ .../features/mulitple-data-in-forms/go.mod | 7 + .../features/mulitple-data-in-forms/go.sum | 13 + .../model_api_response.go | 187 ++++++ .../multiple-files-forms.yaml | 52 ++ .../mulitple-data-in-forms/response.go | 47 ++ .../features/mulitple-data-in-forms/utils.go | 328 +++++++++++ .../go/go-petstore/api_another_fake.go | 6 +- .../petstore/go/go-petstore/api_default.go | 6 +- .../petstore/go/go-petstore/api_fake.go | 112 ++-- .../go-petstore/api_fake_classname_tags123.go | 6 +- .../client/petstore/go/go-petstore/api_pet.go | 96 ++- .../petstore/go/go-petstore/api_store.go | 24 +- .../petstore/go/go-petstore/api_user.go | 48 +- .../client/petstore/go/go-petstore/client.go | 33 +- 38 files changed, 2422 insertions(+), 435 deletions(-) create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/.gitignore create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/.openapi-generator-ignore create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/.openapi-generator/FILES create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/.openapi-generator/VERSION create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/.travis.yml create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/README.md create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/api/openapi.yaml create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/api_default.go create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/client.go create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/configuration.go create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/docs/ApiResponse.md create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/docs/DefaultApi.md create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/git_push.sh create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/go.mod create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/go.sum create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/model_api_response.go create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/multiple-files-forms.yaml create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/response.go create mode 100644 samples/openapi3/client/features/mulitple-data-in-forms/utils.go diff --git a/modules/openapi-generator/src/main/resources/go/api.mustache b/modules/openapi-generator/src/main/resources/go/api.mustache index cabab9ca8fa..4a94d6aaf59 100644 --- a/modules/openapi-generator/src/main/resources/go/api.mustache +++ b/modules/openapi-generator/src/main/resources/go/api.mustache @@ -109,9 +109,7 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class var ( localVarHTTPMethod = _nethttp.Method{{httpMethod}} localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile {{#returnType}} localVarReturnValue {{{.}}} {{/returnType}} @@ -251,22 +249,28 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class {{/headerParams}} {{#formParams}} {{#isFile}} - localVarFormFileName = "{{baseName}}" + var {{paramName}}LocalVarFormFileName string + var {{paramName}}LocalVarFileName string + var {{paramName}}LocalVarFileBytes []byte + + {{paramName}}LocalVarFormFileName = "{{baseName}}" + {{#required}} - localVarFile := *r.{{paramName}} + {{paramName}}LocalVarFile := *r.{{paramName}} {{/required}} {{^required}} - var localVarFile {{dataType}} + var {{paramName}}LocalVarFile {{dataType}} if r.{{paramName}} != nil { - localVarFile = *r.{{paramName}} + {{paramName}}LocalVarFile = *r.{{paramName}} } {{/required}} - if localVarFile != nil { - fbs, _ := _ioutil.ReadAll(localVarFile) - localVarFileBytes = fbs - localVarFileName = localVarFile.Name() - localVarFile.Close() + if {{paramName}}LocalVarFile != nil { + fbs, _ := _ioutil.ReadAll({{paramName}}LocalVarFile) + {{paramName}}LocalVarFileBytes = fbs + {{paramName}}LocalVarFileName = {{paramName}}LocalVarFile.Name() + {{paramName}}LocalVarFile.Close() } + formFiles = append(formFiles, formFile{fileBytes: {{paramName}}LocalVarFileBytes, fileName: {{paramName}}LocalVarFileName, formFileName: {{paramName}}LocalVarFormFileName}) {{/isFile}} {{^isFile}} {{#required}} @@ -330,7 +334,7 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class {{/isKeyInCookie}} {{/isApiKey}} {{/authMethods}} - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err } diff --git a/modules/openapi-generator/src/main/resources/go/client.mustache b/modules/openapi-generator/src/main/resources/go/client.mustache index ace6231a44f..609b362a862 100644 --- a/modules/openapi-generator/src/main/resources/go/client.mustache +++ b/modules/openapi-generator/src/main/resources/go/client.mustache @@ -196,6 +196,12 @@ func (c *APIClient) GetConfig() *Configuration { return c.cfg } +type formFile struct { + fileBytes []byte + fileName string + formFileName string +} + // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, @@ -204,9 +210,7 @@ func (c *APIClient) prepareRequest( headerParams map[string]string, queryParams url.Values, formParams url.Values, - formFileName string, - fileName string, - fileBytes []byte) (localVarRequest *http.Request, err error) { + formFiles []formFile) (localVarRequest *http.Request, err error) { var body *bytes.Buffer @@ -225,7 +229,7 @@ func (c *APIClient) prepareRequest( } // add form parameters and file if available. - if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(formFiles) > 0) { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } @@ -244,16 +248,17 @@ func (c *APIClient) prepareRequest( } } } - 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 + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.fileBytes) + if err != nil { + return nil, err + } } } diff --git a/samples/client/petstore/go/go-petstore/api_another_fake.go b/samples/client/petstore/go/go-petstore/api_another_fake.go index c460926ef23..bb5add0ca9f 100644 --- a/samples/client/petstore/go/go-petstore/api_another_fake.go +++ b/samples/client/petstore/go/go-petstore/api_another_fake.go @@ -80,9 +80,7 @@ func (a *AnotherFakeApiService) Call123TestSpecialTagsExecute(r ApiCall123TestSp var ( localVarHTTPMethod = _nethttp.MethodPatch localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Client ) @@ -119,7 +117,7 @@ func (a *AnotherFakeApiService) Call123TestSpecialTagsExecute(r ApiCall123TestSp } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/client/petstore/go/go-petstore/api_fake.go b/samples/client/petstore/go/go-petstore/api_fake.go index 92bd64eaa92..40252ad41b5 100644 --- a/samples/client/petstore/go/go-petstore/api_fake.go +++ b/samples/client/petstore/go/go-petstore/api_fake.go @@ -252,9 +252,7 @@ func (a *FakeApiService) CreateXmlItemExecute(r ApiCreateXmlItemRequest) (*_neth var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.CreateXmlItem") @@ -290,7 +288,7 @@ func (a *FakeApiService) CreateXmlItemExecute(r ApiCreateXmlItemRequest) (*_neth } // body params localVarPostBody = r.xmlItem - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -355,9 +353,7 @@ func (a *FakeApiService) FakeOuterBooleanSerializeExecute(r ApiFakeOuterBooleanS var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue bool ) @@ -391,7 +387,7 @@ func (a *FakeApiService) FakeOuterBooleanSerializeExecute(r ApiFakeOuterBooleanS } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -465,9 +461,7 @@ func (a *FakeApiService) FakeOuterCompositeSerializeExecute(r ApiFakeOuterCompos var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue OuterComposite ) @@ -501,7 +495,7 @@ func (a *FakeApiService) FakeOuterCompositeSerializeExecute(r ApiFakeOuterCompos } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -575,9 +569,7 @@ func (a *FakeApiService) FakeOuterNumberSerializeExecute(r ApiFakeOuterNumberSer var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue float32 ) @@ -611,7 +603,7 @@ func (a *FakeApiService) FakeOuterNumberSerializeExecute(r ApiFakeOuterNumberSer } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -685,9 +677,7 @@ func (a *FakeApiService) FakeOuterStringSerializeExecute(r ApiFakeOuterStringSer var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue string ) @@ -721,7 +711,7 @@ func (a *FakeApiService) FakeOuterStringSerializeExecute(r ApiFakeOuterStringSer } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -793,9 +783,7 @@ func (a *FakeApiService) TestBodyWithFileSchemaExecute(r ApiTestBodyWithFileSche var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestBodyWithFileSchema") @@ -831,7 +819,7 @@ func (a *FakeApiService) TestBodyWithFileSchemaExecute(r ApiTestBodyWithFileSche } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -897,9 +885,7 @@ func (a *FakeApiService) TestBodyWithQueryParamsExecute(r ApiTestBodyWithQueryPa var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestBodyWithQueryParams") @@ -939,7 +925,7 @@ func (a *FakeApiService) TestBodyWithQueryParamsExecute(r ApiTestBodyWithQueryPa } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1004,9 +990,7 @@ func (a *FakeApiService) TestClientModelExecute(r ApiTestClientModelRequest) (Cl var ( localVarHTTPMethod = _nethttp.MethodPatch localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Client ) @@ -1043,7 +1027,7 @@ func (a *FakeApiService) TestClientModelExecute(r ApiTestClientModelRequest) (Cl } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -1197,9 +1181,7 @@ func (a *FakeApiService) TestEndpointParametersExecute(r ApiTestEndpointParamete var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestEndpointParameters") @@ -1273,17 +1255,23 @@ func (a *FakeApiService) TestEndpointParametersExecute(r ApiTestEndpointParamete } localVarFormParams.Add("pattern_without_delimiter", parameterToString(*r.patternWithoutDelimiter, "")) localVarFormParams.Add("byte", parameterToString(*r.byte_, "")) - localVarFormFileName = "binary" - var localVarFile *os.File + var binaryLocalVarFormFileName string + var binaryLocalVarFileName string + var binaryLocalVarFileBytes []byte + + binaryLocalVarFormFileName = "binary" + + var binaryLocalVarFile *os.File if r.binary != nil { - localVarFile = *r.binary + binaryLocalVarFile = *r.binary } - if localVarFile != nil { - fbs, _ := _ioutil.ReadAll(localVarFile) - localVarFileBytes = fbs - localVarFileName = localVarFile.Name() - localVarFile.Close() + if binaryLocalVarFile != nil { + fbs, _ := _ioutil.ReadAll(binaryLocalVarFile) + binaryLocalVarFileBytes = fbs + binaryLocalVarFileName = binaryLocalVarFile.Name() + binaryLocalVarFile.Close() } + formFiles = append(formFiles, formFile{fileBytes: binaryLocalVarFileBytes, fileName: binaryLocalVarFileName, formFileName: binaryLocalVarFormFileName}) if r.date != nil { localVarFormParams.Add("date", parameterToString(*r.date, "")) } @@ -1296,7 +1284,7 @@ func (a *FakeApiService) TestEndpointParametersExecute(r ApiTestEndpointParamete if r.callback != nil { localVarFormParams.Add("callback", parameterToString(*r.callback, "")) } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1402,9 +1390,7 @@ func (a *FakeApiService) TestEnumParametersExecute(r ApiTestEnumParametersReques var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestEnumParameters") @@ -1459,7 +1445,7 @@ func (a *FakeApiService) TestEnumParametersExecute(r ApiTestEnumParametersReques if r.enumFormString != nil { localVarFormParams.Add("enum_form_string", parameterToString(*r.enumFormString, "")) } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1553,9 +1539,7 @@ func (a *FakeApiService) TestGroupParametersExecute(r ApiTestGroupParametersRequ var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestGroupParameters") @@ -1607,7 +1591,7 @@ func (a *FakeApiService) TestGroupParametersExecute(r ApiTestGroupParametersRequ if r.booleanGroup != nil { localVarHeaderParams["boolean_group"] = parameterToString(*r.booleanGroup, "") } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1669,9 +1653,7 @@ func (a *FakeApiService) TestInlineAdditionalPropertiesExecute(r ApiTestInlineAd var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestInlineAdditionalProperties") @@ -1707,7 +1689,7 @@ func (a *FakeApiService) TestInlineAdditionalPropertiesExecute(r ApiTestInlineAd } // body params localVarPostBody = r.param - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1775,9 +1757,7 @@ func (a *FakeApiService) TestJsonFormDataExecute(r ApiTestJsonFormDataRequest) ( var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestJsonFormData") @@ -1816,7 +1796,7 @@ func (a *FakeApiService) TestJsonFormDataExecute(r ApiTestJsonFormDataRequest) ( } localVarFormParams.Add("param", parameterToString(*r.param, "")) localVarFormParams.Add("param2", parameterToString(*r.param2, "")) - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1899,9 +1879,7 @@ func (a *FakeApiService) TestQueryParameterCollectionFormatExecute(r ApiTestQuer var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestQueryParameterCollectionFormat") @@ -1962,7 +1940,7 @@ func (a *FakeApiService) TestQueryParameterCollectionFormatExecute(r ApiTestQuer if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } diff --git a/samples/client/petstore/go/go-petstore/api_fake_classname_tags123.go b/samples/client/petstore/go/go-petstore/api_fake_classname_tags123.go index cc8592a1a78..67f9f95661a 100644 --- a/samples/client/petstore/go/go-petstore/api_fake_classname_tags123.go +++ b/samples/client/petstore/go/go-petstore/api_fake_classname_tags123.go @@ -80,9 +80,7 @@ func (a *FakeClassnameTags123ApiService) TestClassnameExecute(r ApiTestClassname var ( localVarHTTPMethod = _nethttp.MethodPatch localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Client ) @@ -133,7 +131,7 @@ func (a *FakeClassnameTags123ApiService) TestClassnameExecute(r ApiTestClassname } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/client/petstore/go/go-petstore/api_pet.go b/samples/client/petstore/go/go-petstore/api_pet.go index 9e806f501e5..dc8fe016735 100644 --- a/samples/client/petstore/go/go-petstore/api_pet.go +++ b/samples/client/petstore/go/go-petstore/api_pet.go @@ -183,9 +183,7 @@ func (a *PetApiService) AddPetExecute(r ApiAddPetRequest) (*_nethttp.Response, e var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetApiService.AddPet") @@ -221,7 +219,7 @@ func (a *PetApiService) AddPetExecute(r ApiAddPetRequest) (*_nethttp.Response, e } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -285,9 +283,7 @@ func (a *PetApiService) DeletePetExecute(r ApiDeletePetRequest) (*_nethttp.Respo var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetApiService.DeletePet") @@ -322,7 +318,7 @@ func (a *PetApiService) DeletePetExecute(r ApiDeletePetRequest) (*_nethttp.Respo if r.apiKey != nil { localVarHeaderParams["api_key"] = parameterToString(*r.apiKey, "") } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -387,9 +383,7 @@ func (a *PetApiService) FindPetsByStatusExecute(r ApiFindPetsByStatusRequest) ([ var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Pet ) @@ -425,7 +419,7 @@ func (a *PetApiService) FindPetsByStatusExecute(r ApiFindPetsByStatusRequest) ([ if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -502,9 +496,7 @@ func (a *PetApiService) FindPetsByTagsExecute(r ApiFindPetsByTagsRequest) ([]Pet var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Pet ) @@ -540,7 +532,7 @@ func (a *PetApiService) FindPetsByTagsExecute(r ApiFindPetsByTagsRequest) ([]Pet if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -611,9 +603,7 @@ func (a *PetApiService) GetPetByIdExecute(r ApiGetPetByIdRequest) (Pet, *_nethtt var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Pet ) @@ -660,7 +650,7 @@ func (a *PetApiService) GetPetByIdExecute(r ApiGetPetByIdRequest) (Pet, *_nethtt } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -731,9 +721,7 @@ func (a *PetApiService) UpdatePetExecute(r ApiUpdatePetRequest) (*_nethttp.Respo var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetApiService.UpdatePet") @@ -769,7 +757,7 @@ func (a *PetApiService) UpdatePetExecute(r ApiUpdatePetRequest) (*_nethttp.Respo } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -840,9 +828,7 @@ func (a *PetApiService) UpdatePetWithFormExecute(r ApiUpdatePetWithFormRequest) var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetApiService.UpdatePetWithForm") @@ -880,7 +866,7 @@ func (a *PetApiService) UpdatePetWithFormExecute(r ApiUpdatePetWithFormRequest) if r.status != nil { localVarFormParams.Add("status", parameterToString(*r.status, "")) } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -952,9 +938,7 @@ func (a *PetApiService) UploadFileExecute(r ApiUploadFileRequest) (ApiResponse, var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue ApiResponse ) @@ -990,18 +974,24 @@ func (a *PetApiService) UploadFileExecute(r ApiUploadFileRequest) (ApiResponse, if r.additionalMetadata != nil { localVarFormParams.Add("additionalMetadata", parameterToString(*r.additionalMetadata, "")) } - localVarFormFileName = "file" - var localVarFile *os.File + var fileLocalVarFormFileName string + var fileLocalVarFileName string + var fileLocalVarFileBytes []byte + + fileLocalVarFormFileName = "file" + + var fileLocalVarFile *os.File if r.file != nil { - localVarFile = *r.file + fileLocalVarFile = *r.file } - if localVarFile != nil { - fbs, _ := _ioutil.ReadAll(localVarFile) - localVarFileBytes = fbs - localVarFileName = localVarFile.Name() - localVarFile.Close() + if fileLocalVarFile != nil { + fbs, _ := _ioutil.ReadAll(fileLocalVarFile) + fileLocalVarFileBytes = fbs + fileLocalVarFileName = fileLocalVarFile.Name() + fileLocalVarFile.Close() } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + formFiles = append(formFiles, formFile{fileBytes: fileLocalVarFileBytes, fileName: fileLocalVarFileName, formFileName: fileLocalVarFormFileName}) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -1082,9 +1072,7 @@ func (a *PetApiService) UploadFileWithRequiredFileExecute(r ApiUploadFileWithReq var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue ApiResponse ) @@ -1123,15 +1111,21 @@ func (a *PetApiService) UploadFileWithRequiredFileExecute(r ApiUploadFileWithReq if r.additionalMetadata != nil { localVarFormParams.Add("additionalMetadata", parameterToString(*r.additionalMetadata, "")) } - localVarFormFileName = "requiredFile" - localVarFile := *r.requiredFile - if localVarFile != nil { - fbs, _ := _ioutil.ReadAll(localVarFile) - localVarFileBytes = fbs - localVarFileName = localVarFile.Name() - localVarFile.Close() + var requiredFileLocalVarFormFileName string + var requiredFileLocalVarFileName string + var requiredFileLocalVarFileBytes []byte + + requiredFileLocalVarFormFileName = "requiredFile" + + requiredFileLocalVarFile := *r.requiredFile + if requiredFileLocalVarFile != nil { + fbs, _ := _ioutil.ReadAll(requiredFileLocalVarFile) + requiredFileLocalVarFileBytes = fbs + requiredFileLocalVarFileName = requiredFileLocalVarFile.Name() + requiredFileLocalVarFile.Close() } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + formFiles = append(formFiles, formFile{fileBytes: requiredFileLocalVarFileBytes, fileName: requiredFileLocalVarFileName, formFileName: requiredFileLocalVarFormFileName}) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/client/petstore/go/go-petstore/api_store.go b/samples/client/petstore/go/go-petstore/api_store.go index 0d31a9d574a..be6336216da 100644 --- a/samples/client/petstore/go/go-petstore/api_store.go +++ b/samples/client/petstore/go/go-petstore/api_store.go @@ -118,9 +118,7 @@ func (a *StoreApiService) DeleteOrderExecute(r ApiDeleteOrderRequest) (*_nethttp var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "StoreApiService.DeleteOrder") @@ -152,7 +150,7 @@ func (a *StoreApiService) DeleteOrderExecute(r ApiDeleteOrderRequest) (*_nethttp if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -211,9 +209,7 @@ func (a *StoreApiService) GetInventoryExecute(r ApiGetInventoryRequest) (map[str var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue map[string]int32 ) @@ -259,7 +255,7 @@ func (a *StoreApiService) GetInventoryExecute(r ApiGetInventoryRequest) (map[str } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -330,9 +326,7 @@ func (a *StoreApiService) GetOrderByIdExecute(r ApiGetOrderByIdRequest) (Order, var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Order ) @@ -371,7 +365,7 @@ func (a *StoreApiService) GetOrderByIdExecute(r ApiGetOrderByIdRequest) (Order, if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -443,9 +437,7 @@ func (a *StoreApiService) PlaceOrderExecute(r ApiPlaceOrderRequest) (Order, *_ne var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Order ) @@ -482,7 +474,7 @@ func (a *StoreApiService) PlaceOrderExecute(r ApiPlaceOrderRequest) (Order, *_ne } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/client/petstore/go/go-petstore/api_user.go b/samples/client/petstore/go/go-petstore/api_user.go index b1f6a57f9c4..d6f2c7f710b 100644 --- a/samples/client/petstore/go/go-petstore/api_user.go +++ b/samples/client/petstore/go/go-petstore/api_user.go @@ -165,9 +165,7 @@ func (a *UserApiService) CreateUserExecute(r ApiCreateUserRequest) (*_nethttp.Re var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.CreateUser") @@ -203,7 +201,7 @@ func (a *UserApiService) CreateUserExecute(r ApiCreateUserRequest) (*_nethttp.Re } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -265,9 +263,7 @@ func (a *UserApiService) CreateUsersWithArrayInputExecute(r ApiCreateUsersWithAr var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.CreateUsersWithArrayInput") @@ -303,7 +299,7 @@ func (a *UserApiService) CreateUsersWithArrayInputExecute(r ApiCreateUsersWithAr } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -365,9 +361,7 @@ func (a *UserApiService) CreateUsersWithListInputExecute(r ApiCreateUsersWithLis var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.CreateUsersWithListInput") @@ -403,7 +397,7 @@ func (a *UserApiService) CreateUsersWithListInputExecute(r ApiCreateUsersWithLis } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -464,9 +458,7 @@ func (a *UserApiService) DeleteUserExecute(r ApiDeleteUserRequest) (*_nethttp.Re var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.DeleteUser") @@ -498,7 +490,7 @@ func (a *UserApiService) DeleteUserExecute(r ApiDeleteUserRequest) (*_nethttp.Re if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -558,9 +550,7 @@ func (a *UserApiService) GetUserByNameExecute(r ApiGetUserByNameRequest) (User, var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue User ) @@ -593,7 +583,7 @@ func (a *UserApiService) GetUserByNameExecute(r ApiGetUserByNameRequest) (User, if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -671,9 +661,7 @@ func (a *UserApiService) LoginUserExecute(r ApiLoginUserRequest) (string, *_neth var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue string ) @@ -713,7 +701,7 @@ func (a *UserApiService) LoginUserExecute(r ApiLoginUserRequest) (string, *_neth if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -778,9 +766,7 @@ func (a *UserApiService) LogoutUserExecute(r ApiLogoutUserRequest) (*_nethttp.Re var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.LogoutUser") @@ -811,7 +797,7 @@ func (a *UserApiService) LogoutUserExecute(r ApiLogoutUserRequest) (*_nethttp.Re if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -878,9 +864,7 @@ func (a *UserApiService) UpdateUserExecute(r ApiUpdateUserRequest) (*_nethttp.Re var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.UpdateUser") @@ -917,7 +901,7 @@ func (a *UserApiService) UpdateUserExecute(r ApiUpdateUserRequest) (*_nethttp.Re } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } diff --git a/samples/client/petstore/go/go-petstore/client.go b/samples/client/petstore/go/go-petstore/client.go index efd991f2700..8fbafd32935 100644 --- a/samples/client/petstore/go/go-petstore/client.go +++ b/samples/client/petstore/go/go-petstore/client.go @@ -204,6 +204,12 @@ func (c *APIClient) GetConfig() *Configuration { return c.cfg } +type formFile struct { + fileBytes []byte + fileName string + formFileName string +} + // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, @@ -212,9 +218,7 @@ func (c *APIClient) prepareRequest( headerParams map[string]string, queryParams url.Values, formParams url.Values, - formFileName string, - fileName string, - fileBytes []byte) (localVarRequest *http.Request, err error) { + formFiles []formFile) (localVarRequest *http.Request, err error) { var body *bytes.Buffer @@ -233,7 +237,7 @@ func (c *APIClient) prepareRequest( } // add form parameters and file if available. - if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(formFiles) > 0) { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } @@ -252,16 +256,17 @@ func (c *APIClient) prepareRequest( } } } - 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 + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.fileBytes) + if err != nil { + return nil, err + } } } 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 index d98b721c83d..6e891fbe6fa 100644 --- 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 @@ -57,9 +57,7 @@ func (a *UsageApiService) AnyKeyExecute(r ApiAnyKeyRequest) (map[string]interfac var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue map[string]interface{} ) @@ -119,7 +117,7 @@ func (a *UsageApiService) AnyKeyExecute(r ApiAnyKeyRequest) (map[string]interfac } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -187,9 +185,7 @@ func (a *UsageApiService) BothKeysExecute(r ApiBothKeysRequest) (map[string]inte var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue map[string]interface{} ) @@ -249,7 +245,7 @@ func (a *UsageApiService) BothKeysExecute(r ApiBothKeysRequest) (map[string]inte } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -317,9 +313,7 @@ func (a *UsageApiService) KeyInHeaderExecute(r ApiKeyInHeaderRequest) (map[strin var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue map[string]interface{} ) @@ -365,7 +359,7 @@ func (a *UsageApiService) KeyInHeaderExecute(r ApiKeyInHeaderRequest) (map[strin } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -433,9 +427,7 @@ func (a *UsageApiService) KeyInQueryExecute(r ApiKeyInQueryRequest) (map[string] var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue map[string]interface{} ) @@ -481,7 +473,7 @@ func (a *UsageApiService) KeyInQueryExecute(r ApiKeyInQueryRequest) (map[string] } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } 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 index cdec3821859..f7a7c368cbf 100644 --- 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 @@ -189,6 +189,12 @@ func (c *APIClient) GetConfig() *Configuration { return c.cfg } +type formFile struct { + fileBytes []byte + fileName string + formFileName string +} + // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, @@ -197,9 +203,7 @@ func (c *APIClient) prepareRequest( headerParams map[string]string, queryParams url.Values, formParams url.Values, - formFileName string, - fileName string, - fileBytes []byte) (localVarRequest *http.Request, err error) { + formFiles []formFile) (localVarRequest *http.Request, err error) { var body *bytes.Buffer @@ -218,7 +222,7 @@ func (c *APIClient) prepareRequest( } // add form parameters and file if available. - if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(formFiles) > 0) { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } @@ -237,16 +241,17 @@ func (c *APIClient) prepareRequest( } } } - 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 + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.fileBytes) + if err != nil { + return nil, err + } } } diff --git a/samples/openapi3/client/features/mulitple-data-in-forms/.gitignore b/samples/openapi3/client/features/mulitple-data-in-forms/.gitignore new file mode 100644 index 00000000000..daf913b1b34 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/.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/features/mulitple-data-in-forms/.openapi-generator-ignore b/samples/openapi3/client/features/mulitple-data-in-forms/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/.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/features/mulitple-data-in-forms/.openapi-generator/FILES b/samples/openapi3/client/features/mulitple-data-in-forms/.openapi-generator/FILES new file mode 100644 index 00000000000..c55836136d0 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/.openapi-generator/FILES @@ -0,0 +1,16 @@ +.gitignore +.openapi-generator-ignore +.travis.yml +README.md +api/openapi.yaml +api_default.go +client.go +configuration.go +docs/ApiResponse.md +docs/DefaultApi.md +git_push.sh +go.mod +go.sum +model_api_response.go +response.go +utils.go diff --git a/samples/openapi3/client/features/mulitple-data-in-forms/.openapi-generator/VERSION b/samples/openapi3/client/features/mulitple-data-in-forms/.openapi-generator/VERSION new file mode 100644 index 00000000000..4077803655c --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.1-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/features/mulitple-data-in-forms/.travis.yml b/samples/openapi3/client/features/mulitple-data-in-forms/.travis.yml new file mode 100644 index 00000000000..f5cb2ce9a5a --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/samples/openapi3/client/features/mulitple-data-in-forms/README.md b/samples/openapi3/client/features/mulitple-data-in-forms/README.md new file mode 100644 index 00000000000..76cfee5b404 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/README.md @@ -0,0 +1,113 @@ +# Go API client for openapi + +This is a sample server with a single endpoint that accepts two files via a multipart/form-data POST request. + +## 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.GoClientCodegen + +## 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 "./openapi" +``` + +To use a proxy, set the environment variable `HTTP_PROXY`: + +```golang +os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") +``` + +## 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 identified 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://example.com* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**UploadFiles**](docs/DefaultApi.md#uploadfiles) | **Post** /uploadFiles | uploads two files + + +## Documentation For Models + + - [ApiResponse](docs/ApiResponse.md) + + +## Documentation For Authorization + + Endpoints do not require authorization. + + +## 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/features/mulitple-data-in-forms/api/openapi.yaml b/samples/openapi3/client/features/mulitple-data-in-forms/api/openapi.yaml new file mode 100644 index 00000000000..b849a15b658 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/api/openapi.yaml @@ -0,0 +1,73 @@ +openapi: 3.0.0 +info: + description: This is a sample server with a single endpoint that accepts two files + via a multipart/form-data POST request. + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: Multiple Files via form-data + version: 1.0.0 +servers: +- url: http://example.com +paths: + /uploadFiles: + post: + operationId: uploadFiles + requestBody: + $ref: '#/components/requestBodies/inline_object' + content: + multipart/form-data: + schema: + properties: + file: + description: file to upload + format: binary + type: string + secondFile: + description: another file to upload + format: binary + type: string + type: object + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + summary: uploads two files +components: + requestBodies: + inline_object: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/inline_object' + schemas: + ApiResponse: + description: Describes the result of uploading files + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + title: An uploaded response + type: object + inline_object: + properties: + file: + description: file to upload + format: binary + type: string + secondFile: + description: another file to upload + format: binary + type: string + type: object diff --git a/samples/openapi3/client/features/mulitple-data-in-forms/api_default.go b/samples/openapi3/client/features/mulitple-data-in-forms/api_default.go new file mode 100644 index 00000000000..81c36eb8bb9 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/api_default.go @@ -0,0 +1,172 @@ +/* +Multiple Files via form-data + +This is a sample server with a single endpoint that accepts two files via a multipart/form-data POST request. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + _context "context" + _ioutil "io/ioutil" + _nethttp "net/http" + _neturl "net/url" + "os" +) + +// Linger please +var ( + _ _context.Context +) + +// DefaultApiService DefaultApi service +type DefaultApiService service + +type ApiUploadFilesRequest struct { + ctx _context.Context + ApiService *DefaultApiService + file **os.File + secondFile **os.File +} + +// file to upload +func (r ApiUploadFilesRequest) File(file *os.File) ApiUploadFilesRequest { + r.file = &file + return r +} +// another file to upload +func (r ApiUploadFilesRequest) SecondFile(secondFile *os.File) ApiUploadFilesRequest { + r.secondFile = &secondFile + return r +} + +func (r ApiUploadFilesRequest) Execute() (ApiResponse, *_nethttp.Response, error) { + return r.ApiService.UploadFilesExecute(r) +} + +/* +UploadFiles uploads two files + + @param ctx _context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiUploadFilesRequest +*/ +func (a *DefaultApiService) UploadFiles(ctx _context.Context) ApiUploadFilesRequest { + return ApiUploadFilesRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// @return ApiResponse +func (a *DefaultApiService) UploadFilesExecute(r ApiUploadFilesRequest) (ApiResponse, *_nethttp.Response, error) { + var ( + localVarHTTPMethod = _nethttp.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue ApiResponse + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "DefaultApiService.UploadFiles") + if err != nil { + return localVarReturnValue, nil, GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/uploadFiles" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := _neturl.Values{} + localVarFormParams := _neturl.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"multipart/form-data"} + + // 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 + } + var fileLocalVarFormFileName string + var fileLocalVarFileName string + var fileLocalVarFileBytes []byte + + fileLocalVarFormFileName = "file" + + var fileLocalVarFile *os.File + if r.file != nil { + fileLocalVarFile = *r.file + } + if fileLocalVarFile != nil { + fbs, _ := _ioutil.ReadAll(fileLocalVarFile) + fileLocalVarFileBytes = fbs + fileLocalVarFileName = fileLocalVarFile.Name() + fileLocalVarFile.Close() + } + formFiles = append(formFiles, formFile{fileBytes: fileLocalVarFileBytes, fileName: fileLocalVarFileName, formFileName: fileLocalVarFormFileName}) + var secondFileLocalVarFormFileName string + var secondFileLocalVarFileName string + var secondFileLocalVarFileBytes []byte + + secondFileLocalVarFormFileName = "secondFile" + + var secondFileLocalVarFile *os.File + if r.secondFile != nil { + secondFileLocalVarFile = *r.secondFile + } + if secondFileLocalVarFile != nil { + fbs, _ := _ioutil.ReadAll(secondFileLocalVarFile) + secondFileLocalVarFileBytes = fbs + secondFileLocalVarFileName = secondFileLocalVarFile.Name() + secondFileLocalVarFile.Close() + } + formFiles = append(formFiles, formFile{fileBytes: secondFileLocalVarFileBytes, fileName: secondFileLocalVarFileName, formFileName: secondFileLocalVarFormFileName}) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := _ioutil.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = _ioutil.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.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/features/mulitple-data-in-forms/client.go b/samples/openapi3/client/features/mulitple-data-in-forms/client.go new file mode 100644 index 00000000000..3d2f9db38b6 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/client.go @@ -0,0 +1,553 @@ +/* +Multiple Files via form-data + +This is a sample server with a single endpoint that accepts two files via a multipart/form-data POST request. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "io/ioutil" + "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 Multiple Files via form-data 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 + + DefaultApi *DefaultApiService +} + +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.DefaultApi = (*DefaultApiService)(&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 insensitive 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 +} + +type formFile struct { + fileBytes []byte + fileName string + formFileName string +} + +// 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, + formFiles []formFile) (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(formFiles) > 0) { + 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) + } + } + } + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.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 f, ok := v.(**os.File); ok { + *f, err = ioutil.TempFile("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + if err != nil { + return + } + _, err = (*f).Seek(0, io.SeekStart) + return + } + 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 { + return 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 fp, ok := body.(**os.File); ok { + _, err = bodyBuf.ReadFrom(*fp) + } 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/features/mulitple-data-in-forms/configuration.go b/samples/openapi3/client/features/mulitple-data-in-forms/configuration.go new file mode 100644 index 00000000000..b37e37f59eb --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/configuration.go @@ -0,0 +1,230 @@ +/* +Multiple Files via form-data + +This is a sample server with a single endpoint that accepts two files via a multipart/form-data POST request. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +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://example.com", + Description: "No description provided", + }, + }, + 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/features/mulitple-data-in-forms/docs/ApiResponse.md b/samples/openapi3/client/features/mulitple-data-in-forms/docs/ApiResponse.md new file mode 100644 index 00000000000..877dacb4293 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/docs/ApiResponse.md @@ -0,0 +1,108 @@ +# ApiResponse + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Code** | Pointer to **int32** | | [optional] +**Type** | Pointer to **string** | | [optional] +**Message** | Pointer to **string** | | [optional] + +## Methods + +### NewApiResponse + +`func NewApiResponse() *ApiResponse` + +NewApiResponse instantiates a new ApiResponse object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewApiResponseWithDefaults + +`func NewApiResponseWithDefaults() *ApiResponse` + +NewApiResponseWithDefaults instantiates a new ApiResponse object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetCode + +`func (o *ApiResponse) GetCode() int32` + +GetCode returns the Code field if non-nil, zero value otherwise. + +### GetCodeOk + +`func (o *ApiResponse) GetCodeOk() (*int32, bool)` + +GetCodeOk returns a tuple with the Code field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetCode + +`func (o *ApiResponse) SetCode(v int32)` + +SetCode sets Code field to given value. + +### HasCode + +`func (o *ApiResponse) HasCode() bool` + +HasCode returns a boolean if a field has been set. + +### GetType + +`func (o *ApiResponse) GetType() string` + +GetType returns the Type field if non-nil, zero value otherwise. + +### GetTypeOk + +`func (o *ApiResponse) GetTypeOk() (*string, bool)` + +GetTypeOk returns a tuple with the Type field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetType + +`func (o *ApiResponse) SetType(v string)` + +SetType sets Type field to given value. + +### HasType + +`func (o *ApiResponse) HasType() bool` + +HasType returns a boolean if a field has been set. + +### GetMessage + +`func (o *ApiResponse) GetMessage() string` + +GetMessage returns the Message field if non-nil, zero value otherwise. + +### GetMessageOk + +`func (o *ApiResponse) GetMessageOk() (*string, bool)` + +GetMessageOk returns a tuple with the Message field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetMessage + +`func (o *ApiResponse) SetMessage(v string)` + +SetMessage sets Message field to given value. + +### HasMessage + +`func (o *ApiResponse) HasMessage() bool` + +HasMessage returns a boolean if a field has been set. + + +[[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/openapi3/client/features/mulitple-data-in-forms/docs/DefaultApi.md b/samples/openapi3/client/features/mulitple-data-in-forms/docs/DefaultApi.md new file mode 100644 index 00000000000..fc5678d9345 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/docs/DefaultApi.md @@ -0,0 +1,75 @@ +# \DefaultApi + +All URIs are relative to *http://example.com* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**UploadFiles**](DefaultApi.md#UploadFiles) | **Post** /uploadFiles | uploads two files + + + +## UploadFiles + +> ApiResponse UploadFiles(ctx).File(file).SecondFile(secondFile).Execute() + +uploads two files + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "./openapi" +) + +func main() { + file := os.NewFile(1234, "some_file") // *os.File | file to upload (optional) + secondFile := os.NewFile(1234, "some_file") // *os.File | another file to upload (optional) + + configuration := openapiclient.NewConfiguration() + api_client := openapiclient.NewAPIClient(configuration) + resp, r, err := api_client.DefaultApi.UploadFiles(context.Background()).File(file).SecondFile(secondFile).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `DefaultApi.UploadFiles``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `UploadFiles`: ApiResponse + fmt.Fprintf(os.Stdout, "Response from `DefaultApi.UploadFiles`: %v\n", resp) +} +``` + +### Path Parameters + + + +### Other Parameters + +Other parameters are passed through a pointer to a apiUploadFilesRequest struct via the builder pattern + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **file** | ***os.File** | file to upload | + **secondFile** | ***os.File** | another file to upload | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **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/features/mulitple-data-in-forms/git_push.sh b/samples/openapi3/client/features/mulitple-data-in-forms/git_push.sh new file mode 100644 index 00000000000..f53a75d4fab --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/git_push.sh @@ -0,0 +1,57 @@ +#!/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-petstore-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/features/mulitple-data-in-forms/go.mod b/samples/openapi3/client/features/mulitple-data-in-forms/go.mod new file mode 100644 index 00000000000..0f43de9ebb2 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/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-20210218202405-ba52d332ba99 +) diff --git a/samples/openapi3/client/features/mulitple-data-in-forms/go.sum b/samples/openapi3/client/features/mulitple-data-in-forms/go.sum new file mode 100644 index 00000000000..734252e6815 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/go.sum @@ -0,0 +1,13 @@ +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +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/features/mulitple-data-in-forms/model_api_response.go b/samples/openapi3/client/features/mulitple-data-in-forms/model_api_response.go new file mode 100644 index 00000000000..d1fee6092d1 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/model_api_response.go @@ -0,0 +1,187 @@ +/* +Multiple Files via form-data + +This is a sample server with a single endpoint that accepts two files via a multipart/form-data POST request. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" +) + +// ApiResponse Describes the result of uploading files +type ApiResponse struct { + Code *int32 `json:"code,omitempty"` + Type *string `json:"type,omitempty"` + Message *string `json:"message,omitempty"` +} + +// NewApiResponse instantiates a new ApiResponse object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewApiResponse() *ApiResponse { + this := ApiResponse{} + return &this +} + +// NewApiResponseWithDefaults instantiates a new ApiResponse object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewApiResponseWithDefaults() *ApiResponse { + this := ApiResponse{} + return &this +} + +// GetCode returns the Code field value if set, zero value otherwise. +func (o *ApiResponse) GetCode() int32 { + if o == nil || o.Code == nil { + var ret int32 + return ret + } + return *o.Code +} + +// GetCodeOk returns a tuple with the Code field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ApiResponse) GetCodeOk() (*int32, bool) { + if o == nil || o.Code == nil { + return nil, false + } + return o.Code, true +} + +// HasCode returns a boolean if a field has been set. +func (o *ApiResponse) HasCode() bool { + if o != nil && o.Code != nil { + return true + } + + return false +} + +// SetCode gets a reference to the given int32 and assigns it to the Code field. +func (o *ApiResponse) SetCode(v int32) { + o.Code = &v +} + +// GetType returns the Type field value if set, zero value otherwise. +func (o *ApiResponse) GetType() string { + if o == nil || o.Type == nil { + var ret string + return ret + } + return *o.Type +} + +// GetTypeOk returns a tuple with the Type field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ApiResponse) GetTypeOk() (*string, bool) { + if o == nil || o.Type == nil { + return nil, false + } + return o.Type, true +} + +// HasType returns a boolean if a field has been set. +func (o *ApiResponse) HasType() bool { + if o != nil && o.Type != nil { + return true + } + + return false +} + +// SetType gets a reference to the given string and assigns it to the Type field. +func (o *ApiResponse) SetType(v string) { + o.Type = &v +} + +// GetMessage returns the Message field value if set, zero value otherwise. +func (o *ApiResponse) GetMessage() string { + if o == nil || o.Message == nil { + var ret string + return ret + } + return *o.Message +} + +// GetMessageOk returns a tuple with the Message field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ApiResponse) GetMessageOk() (*string, bool) { + if o == nil || o.Message == nil { + return nil, false + } + return o.Message, true +} + +// HasMessage returns a boolean if a field has been set. +func (o *ApiResponse) HasMessage() bool { + if o != nil && o.Message != nil { + return true + } + + return false +} + +// SetMessage gets a reference to the given string and assigns it to the Message field. +func (o *ApiResponse) SetMessage(v string) { + o.Message = &v +} + +func (o ApiResponse) MarshalJSON() ([]byte, error) { + toSerialize := map[string]interface{}{} + if o.Code != nil { + toSerialize["code"] = o.Code + } + if o.Type != nil { + toSerialize["type"] = o.Type + } + if o.Message != nil { + toSerialize["message"] = o.Message + } + return json.Marshal(toSerialize) +} + +type NullableApiResponse struct { + value *ApiResponse + isSet bool +} + +func (v NullableApiResponse) Get() *ApiResponse { + return v.value +} + +func (v *NullableApiResponse) Set(val *ApiResponse) { + v.value = val + v.isSet = true +} + +func (v NullableApiResponse) IsSet() bool { + return v.isSet +} + +func (v *NullableApiResponse) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableApiResponse(val *ApiResponse) *NullableApiResponse { + return &NullableApiResponse{value: val, isSet: true} +} + +func (v NullableApiResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableApiResponse) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/features/mulitple-data-in-forms/multiple-files-forms.yaml b/samples/openapi3/client/features/mulitple-data-in-forms/multiple-files-forms.yaml new file mode 100644 index 00000000000..fd522ba72c4 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/multiple-files-forms.yaml @@ -0,0 +1,52 @@ +openapi: 3.0.0 +servers: + - url: "http://example.com" +info: + description: >- + This is a sample server with a single endpoint that accepts two files via a multipart/form-data POST request. + version: 1.0.0 + title: Multiple Files via form-data + license: + name: Apache-2.0 + url: "https://www.apache.org/licenses/LICENSE-2.0.html" +paths: + "/uploadFiles": + post: + summary: uploads two files + description: "" + operationId: uploadFiles + responses: + "200": + description: successful operation + content: + application/json: + schema: + $ref: "#/components/schemas/ApiResponse" + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + file: + description: file to upload + type: string + format: binary + secondFile: + description: another file to upload + type: string + format: binary +components: + schemas: + ApiResponse: + title: An uploaded response + description: Describes the result of uploading files + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string diff --git a/samples/openapi3/client/features/mulitple-data-in-forms/response.go b/samples/openapi3/client/features/mulitple-data-in-forms/response.go new file mode 100644 index 00000000000..f6fa23e6e01 --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/response.go @@ -0,0 +1,47 @@ +/* +Multiple Files via form-data + +This is a sample server with a single endpoint that accepts two files via a multipart/form-data POST request. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +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 APIResponse 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/features/mulitple-data-in-forms/utils.go b/samples/openapi3/client/features/mulitple-data-in-forms/utils.go new file mode 100644 index 00000000000..b687a2ee01c --- /dev/null +++ b/samples/openapi3/client/features/mulitple-data-in-forms/utils.go @@ -0,0 +1,328 @@ +/* +Multiple Files via form-data + +This is a sample server with a single endpoint that accepts two files via a multipart/form-data POST request. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package openapi + +import ( + "encoding/json" + "time" +) + +// PtrBool is a helper routine that returns a pointer to given boolean 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/petstore/go/go-petstore/api_another_fake.go b/samples/openapi3/client/petstore/go/go-petstore/api_another_fake.go index 7fd48ba7647..640c21d7250 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_another_fake.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_another_fake.go @@ -80,9 +80,7 @@ func (a *AnotherFakeApiService) Call123TestSpecialTagsExecute(r ApiCall123TestSp var ( localVarHTTPMethod = _nethttp.MethodPatch localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Client ) @@ -119,7 +117,7 @@ func (a *AnotherFakeApiService) Call123TestSpecialTagsExecute(r ApiCall123TestSp } // body params localVarPostBody = r.client - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_default.go b/samples/openapi3/client/petstore/go/go-petstore/api_default.go index 1b75b59c713..be637eceddf 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_default.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_default.go @@ -70,9 +70,7 @@ func (a *DefaultApiService) FooGetExecute(r ApiFooGetRequest) (InlineResponseDef var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue InlineResponseDefault ) @@ -104,7 +102,7 @@ func (a *DefaultApiService) FooGetExecute(r ApiFooGetRequest) (InlineResponseDef if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_fake.go b/samples/openapi3/client/petstore/go/go-petstore/api_fake.go index bcdf35e0231..a2cb81b7fea 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_fake.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_fake.go @@ -259,9 +259,7 @@ func (a *FakeApiService) FakeHealthGetExecute(r ApiFakeHealthGetRequest) (Health var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue HealthCheckResult ) @@ -293,7 +291,7 @@ func (a *FakeApiService) FakeHealthGetExecute(r ApiFakeHealthGetRequest) (Health if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -367,9 +365,7 @@ func (a *FakeApiService) FakeOuterBooleanSerializeExecute(r ApiFakeOuterBooleanS var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue bool ) @@ -403,7 +399,7 @@ func (a *FakeApiService) FakeOuterBooleanSerializeExecute(r ApiFakeOuterBooleanS } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -477,9 +473,7 @@ func (a *FakeApiService) FakeOuterCompositeSerializeExecute(r ApiFakeOuterCompos var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue OuterComposite ) @@ -513,7 +507,7 @@ func (a *FakeApiService) FakeOuterCompositeSerializeExecute(r ApiFakeOuterCompos } // body params localVarPostBody = r.outerComposite - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -587,9 +581,7 @@ func (a *FakeApiService) FakeOuterNumberSerializeExecute(r ApiFakeOuterNumberSer var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue float32 ) @@ -623,7 +615,7 @@ func (a *FakeApiService) FakeOuterNumberSerializeExecute(r ApiFakeOuterNumberSer } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -697,9 +689,7 @@ func (a *FakeApiService) FakeOuterStringSerializeExecute(r ApiFakeOuterStringSer var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue string ) @@ -733,7 +723,7 @@ func (a *FakeApiService) FakeOuterStringSerializeExecute(r ApiFakeOuterStringSer } // body params localVarPostBody = r.body - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -805,9 +795,7 @@ func (a *FakeApiService) TestBodyWithFileSchemaExecute(r ApiTestBodyWithFileSche var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestBodyWithFileSchema") @@ -843,7 +831,7 @@ func (a *FakeApiService) TestBodyWithFileSchemaExecute(r ApiTestBodyWithFileSche } // body params localVarPostBody = r.fileSchemaTestClass - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -909,9 +897,7 @@ func (a *FakeApiService) TestBodyWithQueryParamsExecute(r ApiTestBodyWithQueryPa var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestBodyWithQueryParams") @@ -951,7 +937,7 @@ func (a *FakeApiService) TestBodyWithQueryParamsExecute(r ApiTestBodyWithQueryPa } // body params localVarPostBody = r.user - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1016,9 +1002,7 @@ func (a *FakeApiService) TestClientModelExecute(r ApiTestClientModelRequest) (Cl var ( localVarHTTPMethod = _nethttp.MethodPatch localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Client ) @@ -1055,7 +1039,7 @@ func (a *FakeApiService) TestClientModelExecute(r ApiTestClientModelRequest) (Cl } // body params localVarPostBody = r.client - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -1210,9 +1194,7 @@ func (a *FakeApiService) TestEndpointParametersExecute(r ApiTestEndpointParamete var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestEndpointParameters") @@ -1286,17 +1268,23 @@ func (a *FakeApiService) TestEndpointParametersExecute(r ApiTestEndpointParamete } localVarFormParams.Add("pattern_without_delimiter", parameterToString(*r.patternWithoutDelimiter, "")) localVarFormParams.Add("byte", parameterToString(*r.byte_, "")) - localVarFormFileName = "binary" - var localVarFile *os.File + var binaryLocalVarFormFileName string + var binaryLocalVarFileName string + var binaryLocalVarFileBytes []byte + + binaryLocalVarFormFileName = "binary" + + var binaryLocalVarFile *os.File if r.binary != nil { - localVarFile = *r.binary + binaryLocalVarFile = *r.binary } - if localVarFile != nil { - fbs, _ := _ioutil.ReadAll(localVarFile) - localVarFileBytes = fbs - localVarFileName = localVarFile.Name() - localVarFile.Close() + if binaryLocalVarFile != nil { + fbs, _ := _ioutil.ReadAll(binaryLocalVarFile) + binaryLocalVarFileBytes = fbs + binaryLocalVarFileName = binaryLocalVarFile.Name() + binaryLocalVarFile.Close() } + formFiles = append(formFiles, formFile{fileBytes: binaryLocalVarFileBytes, fileName: binaryLocalVarFileName, formFileName: binaryLocalVarFormFileName}) if r.date != nil { localVarFormParams.Add("date", parameterToString(*r.date, "")) } @@ -1309,7 +1297,7 @@ func (a *FakeApiService) TestEndpointParametersExecute(r ApiTestEndpointParamete if r.callback != nil { localVarFormParams.Add("callback", parameterToString(*r.callback, "")) } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1415,9 +1403,7 @@ func (a *FakeApiService) TestEnumParametersExecute(r ApiTestEnumParametersReques var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestEnumParameters") @@ -1480,7 +1466,7 @@ func (a *FakeApiService) TestEnumParametersExecute(r ApiTestEnumParametersReques if r.enumFormString != nil { localVarFormParams.Add("enum_form_string", parameterToString(*r.enumFormString, "")) } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1574,9 +1560,7 @@ func (a *FakeApiService) TestGroupParametersExecute(r ApiTestGroupParametersRequ var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestGroupParameters") @@ -1628,7 +1612,7 @@ func (a *FakeApiService) TestGroupParametersExecute(r ApiTestGroupParametersRequ if r.booleanGroup != nil { localVarHeaderParams["boolean_group"] = parameterToString(*r.booleanGroup, "") } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1690,9 +1674,7 @@ func (a *FakeApiService) TestInlineAdditionalPropertiesExecute(r ApiTestInlineAd var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestInlineAdditionalProperties") @@ -1728,7 +1710,7 @@ func (a *FakeApiService) TestInlineAdditionalPropertiesExecute(r ApiTestInlineAd } // body params localVarPostBody = r.requestBody - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1796,9 +1778,7 @@ func (a *FakeApiService) TestJsonFormDataExecute(r ApiTestJsonFormDataRequest) ( var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestJsonFormData") @@ -1837,7 +1817,7 @@ func (a *FakeApiService) TestJsonFormDataExecute(r ApiTestJsonFormDataRequest) ( } localVarFormParams.Add("param", parameterToString(*r.param, "")) localVarFormParams.Add("param2", parameterToString(*r.param2, "")) - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -1920,9 +1900,7 @@ func (a *FakeApiService) TestQueryParameterCollectionFormatExecute(r ApiTestQuer var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeApiService.TestQueryParameterCollectionFormat") @@ -1993,7 +1971,7 @@ func (a *FakeApiService) TestQueryParameterCollectionFormatExecute(r ApiTestQuer if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -2062,9 +2040,7 @@ func (a *FakeApiService) TestUniqueItemsHeaderAndQueryParameterCollectionFormatE var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Pet ) @@ -2114,7 +2090,7 @@ func (a *FakeApiService) TestUniqueItemsHeaderAndQueryParameterCollectionFormatE localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } localVarHeaderParams["headerUnique"] = parameterToString(*r.headerUnique, "csv") - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_fake_classname_tags123.go b/samples/openapi3/client/petstore/go/go-petstore/api_fake_classname_tags123.go index 2ddc5ebf7da..a9e7b6279f3 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_fake_classname_tags123.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_fake_classname_tags123.go @@ -80,9 +80,7 @@ func (a *FakeClassnameTags123ApiService) TestClassnameExecute(r ApiTestClassname var ( localVarHTTPMethod = _nethttp.MethodPatch localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Client ) @@ -133,7 +131,7 @@ func (a *FakeClassnameTags123ApiService) TestClassnameExecute(r ApiTestClassname } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_pet.go b/samples/openapi3/client/petstore/go/go-petstore/api_pet.go index 9f172c3cd30..0b50bc15c5e 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_pet.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_pet.go @@ -183,9 +183,7 @@ func (a *PetApiService) AddPetExecute(r ApiAddPetRequest) (*_nethttp.Response, e var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetApiService.AddPet") @@ -221,7 +219,7 @@ func (a *PetApiService) AddPetExecute(r ApiAddPetRequest) (*_nethttp.Response, e } // body params localVarPostBody = r.pet - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -285,9 +283,7 @@ func (a *PetApiService) DeletePetExecute(r ApiDeletePetRequest) (*_nethttp.Respo var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetApiService.DeletePet") @@ -322,7 +318,7 @@ func (a *PetApiService) DeletePetExecute(r ApiDeletePetRequest) (*_nethttp.Respo if r.apiKey != nil { localVarHeaderParams["api_key"] = parameterToString(*r.apiKey, "") } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -388,9 +384,7 @@ func (a *PetApiService) FindPetsByStatusExecute(r ApiFindPetsByStatusRequest) ([ var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Pet ) @@ -426,7 +420,7 @@ func (a *PetApiService) FindPetsByStatusExecute(r ApiFindPetsByStatusRequest) ([ if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -503,9 +497,7 @@ func (a *PetApiService) FindPetsByTagsExecute(r ApiFindPetsByTagsRequest) ([]Pet var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Pet ) @@ -541,7 +533,7 @@ func (a *PetApiService) FindPetsByTagsExecute(r ApiFindPetsByTagsRequest) ([]Pet if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -612,9 +604,7 @@ func (a *PetApiService) GetPetByIdExecute(r ApiGetPetByIdRequest) (Pet, *_nethtt var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Pet ) @@ -661,7 +651,7 @@ func (a *PetApiService) GetPetByIdExecute(r ApiGetPetByIdRequest) (Pet, *_nethtt } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -732,9 +722,7 @@ func (a *PetApiService) UpdatePetExecute(r ApiUpdatePetRequest) (*_nethttp.Respo var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetApiService.UpdatePet") @@ -770,7 +758,7 @@ func (a *PetApiService) UpdatePetExecute(r ApiUpdatePetRequest) (*_nethttp.Respo } // body params localVarPostBody = r.pet - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -841,9 +829,7 @@ func (a *PetApiService) UpdatePetWithFormExecute(r ApiUpdatePetWithFormRequest) var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetApiService.UpdatePetWithForm") @@ -881,7 +867,7 @@ func (a *PetApiService) UpdatePetWithFormExecute(r ApiUpdatePetWithFormRequest) if r.status != nil { localVarFormParams.Add("status", parameterToString(*r.status, "")) } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -953,9 +939,7 @@ func (a *PetApiService) UploadFileExecute(r ApiUploadFileRequest) (ApiResponse, var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue ApiResponse ) @@ -991,18 +975,24 @@ func (a *PetApiService) UploadFileExecute(r ApiUploadFileRequest) (ApiResponse, if r.additionalMetadata != nil { localVarFormParams.Add("additionalMetadata", parameterToString(*r.additionalMetadata, "")) } - localVarFormFileName = "file" - var localVarFile *os.File + var fileLocalVarFormFileName string + var fileLocalVarFileName string + var fileLocalVarFileBytes []byte + + fileLocalVarFormFileName = "file" + + var fileLocalVarFile *os.File if r.file != nil { - localVarFile = *r.file + fileLocalVarFile = *r.file } - if localVarFile != nil { - fbs, _ := _ioutil.ReadAll(localVarFile) - localVarFileBytes = fbs - localVarFileName = localVarFile.Name() - localVarFile.Close() + if fileLocalVarFile != nil { + fbs, _ := _ioutil.ReadAll(fileLocalVarFile) + fileLocalVarFileBytes = fbs + fileLocalVarFileName = fileLocalVarFile.Name() + fileLocalVarFile.Close() } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + formFiles = append(formFiles, formFile{fileBytes: fileLocalVarFileBytes, fileName: fileLocalVarFileName, formFileName: fileLocalVarFormFileName}) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -1083,9 +1073,7 @@ func (a *PetApiService) UploadFileWithRequiredFileExecute(r ApiUploadFileWithReq var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue ApiResponse ) @@ -1124,15 +1112,21 @@ func (a *PetApiService) UploadFileWithRequiredFileExecute(r ApiUploadFileWithReq if r.additionalMetadata != nil { localVarFormParams.Add("additionalMetadata", parameterToString(*r.additionalMetadata, "")) } - localVarFormFileName = "requiredFile" - localVarFile := *r.requiredFile - if localVarFile != nil { - fbs, _ := _ioutil.ReadAll(localVarFile) - localVarFileBytes = fbs - localVarFileName = localVarFile.Name() - localVarFile.Close() + var requiredFileLocalVarFormFileName string + var requiredFileLocalVarFileName string + var requiredFileLocalVarFileBytes []byte + + requiredFileLocalVarFormFileName = "requiredFile" + + requiredFileLocalVarFile := *r.requiredFile + if requiredFileLocalVarFile != nil { + fbs, _ := _ioutil.ReadAll(requiredFileLocalVarFile) + requiredFileLocalVarFileBytes = fbs + requiredFileLocalVarFileName = requiredFileLocalVarFile.Name() + requiredFileLocalVarFile.Close() } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + formFiles = append(formFiles, formFile{fileBytes: requiredFileLocalVarFileBytes, fileName: requiredFileLocalVarFileName, formFileName: requiredFileLocalVarFormFileName}) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_store.go b/samples/openapi3/client/petstore/go/go-petstore/api_store.go index 1fb82f576fa..41c9e8fda94 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_store.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_store.go @@ -118,9 +118,7 @@ func (a *StoreApiService) DeleteOrderExecute(r ApiDeleteOrderRequest) (*_nethttp var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "StoreApiService.DeleteOrder") @@ -152,7 +150,7 @@ func (a *StoreApiService) DeleteOrderExecute(r ApiDeleteOrderRequest) (*_nethttp if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -211,9 +209,7 @@ func (a *StoreApiService) GetInventoryExecute(r ApiGetInventoryRequest) (map[str var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue map[string]int32 ) @@ -259,7 +255,7 @@ func (a *StoreApiService) GetInventoryExecute(r ApiGetInventoryRequest) (map[str } } } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -330,9 +326,7 @@ func (a *StoreApiService) GetOrderByIdExecute(r ApiGetOrderByIdRequest) (Order, var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Order ) @@ -371,7 +365,7 @@ func (a *StoreApiService) GetOrderByIdExecute(r ApiGetOrderByIdRequest) (Order, if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -443,9 +437,7 @@ func (a *StoreApiService) PlaceOrderExecute(r ApiPlaceOrderRequest) (Order, *_ne var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue Order ) @@ -482,7 +474,7 @@ func (a *StoreApiService) PlaceOrderExecute(r ApiPlaceOrderRequest) (Order, *_ne } // body params localVarPostBody = r.order - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_user.go b/samples/openapi3/client/petstore/go/go-petstore/api_user.go index 0c259b33c4f..d67bb32a7e0 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_user.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_user.go @@ -165,9 +165,7 @@ func (a *UserApiService) CreateUserExecute(r ApiCreateUserRequest) (*_nethttp.Re var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.CreateUser") @@ -203,7 +201,7 @@ func (a *UserApiService) CreateUserExecute(r ApiCreateUserRequest) (*_nethttp.Re } // body params localVarPostBody = r.user - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -265,9 +263,7 @@ func (a *UserApiService) CreateUsersWithArrayInputExecute(r ApiCreateUsersWithAr var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.CreateUsersWithArrayInput") @@ -303,7 +299,7 @@ func (a *UserApiService) CreateUsersWithArrayInputExecute(r ApiCreateUsersWithAr } // body params localVarPostBody = r.user - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -365,9 +361,7 @@ func (a *UserApiService) CreateUsersWithListInputExecute(r ApiCreateUsersWithLis var ( localVarHTTPMethod = _nethttp.MethodPost localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.CreateUsersWithListInput") @@ -403,7 +397,7 @@ func (a *UserApiService) CreateUsersWithListInputExecute(r ApiCreateUsersWithLis } // body params localVarPostBody = r.user - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -464,9 +458,7 @@ func (a *UserApiService) DeleteUserExecute(r ApiDeleteUserRequest) (*_nethttp.Re var ( localVarHTTPMethod = _nethttp.MethodDelete localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.DeleteUser") @@ -498,7 +490,7 @@ func (a *UserApiService) DeleteUserExecute(r ApiDeleteUserRequest) (*_nethttp.Re if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -558,9 +550,7 @@ func (a *UserApiService) GetUserByNameExecute(r ApiGetUserByNameRequest) (User, var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue User ) @@ -593,7 +583,7 @@ func (a *UserApiService) GetUserByNameExecute(r ApiGetUserByNameRequest) (User, if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -671,9 +661,7 @@ func (a *UserApiService) LoginUserExecute(r ApiLoginUserRequest) (string, *_neth var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue string ) @@ -713,7 +701,7 @@ func (a *UserApiService) LoginUserExecute(r ApiLoginUserRequest) (string, *_neth if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } @@ -778,9 +766,7 @@ func (a *UserApiService) LogoutUserExecute(r ApiLogoutUserRequest) (*_nethttp.Re var ( localVarHTTPMethod = _nethttp.MethodGet localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.LogoutUser") @@ -811,7 +797,7 @@ func (a *UserApiService) LogoutUserExecute(r ApiLogoutUserRequest) (*_nethttp.Re if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } @@ -878,9 +864,7 @@ func (a *UserApiService) UpdateUserExecute(r ApiUpdateUserRequest) (*_nethttp.Re var ( localVarHTTPMethod = _nethttp.MethodPut localVarPostBody interface{} - localVarFormFileName string - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "UserApiService.UpdateUser") @@ -917,7 +901,7 @@ func (a *UserApiService) UpdateUserExecute(r ApiUpdateUserRequest) (*_nethttp.Re } // body params localVarPostBody = r.user - req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } diff --git a/samples/openapi3/client/petstore/go/go-petstore/client.go b/samples/openapi3/client/petstore/go/go-petstore/client.go index 99cd5b9ef28..99eed71f66f 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/client.go +++ b/samples/openapi3/client/petstore/go/go-petstore/client.go @@ -207,6 +207,12 @@ func (c *APIClient) GetConfig() *Configuration { return c.cfg } +type formFile struct { + fileBytes []byte + fileName string + formFileName string +} + // prepareRequest build the request func (c *APIClient) prepareRequest( ctx context.Context, @@ -215,9 +221,7 @@ func (c *APIClient) prepareRequest( headerParams map[string]string, queryParams url.Values, formParams url.Values, - formFileName string, - fileName string, - fileBytes []byte) (localVarRequest *http.Request, err error) { + formFiles []formFile) (localVarRequest *http.Request, err error) { var body *bytes.Buffer @@ -236,7 +240,7 @@ func (c *APIClient) prepareRequest( } // add form parameters and file if available. - if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(formFiles) > 0) { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } @@ -255,16 +259,17 @@ func (c *APIClient) prepareRequest( } } } - 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 + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.fileBytes) + if err != nil { + return nil, err + } } } From fdea71b26eb0bfcc4ff7e48b15463e63c5a1a6ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C4=8Cerm=C3=A1k?= <64807060+Yurzel@users.noreply.github.com> Date: Mon, 22 Nov 2021 09:29:09 +0100 Subject: [PATCH 04/61] [Protobuf-Schema] Add enum as model support (#10868) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [Protobuf-Schema] Add enum as model support * [Protobuf-Schema] Bugfix: Reverted classname modification * [Protobuf-Scheme] Mustache newlines update * [Protobuf-Schema] Renamed addModelEnumIndexes to addEnumIndexes * [Protobuf-Schema] Add enum as model support * [Protobuf-Schema] Bugfix: Reverted classname modification * [Protobuf-Scheme] Mustache newlines update * [Protobuf-Schema] Renamed addModelEnumIndexes to addEnumIndexes Co-authored-by: Tomáš Čermák --- .../languages/ProtobufSchemaCodegen.java | 24 ++++++++++++++----- .../resources/protobuf-schema/enum.mustache | 7 ++++++ .../resources/protobuf-schema/model.mustache | 3 ++- 3 files changed, 27 insertions(+), 7 deletions(-) create mode 100644 modules/openapi-generator/src/main/resources/protobuf-schema/enum.mustache diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java index f04a58fcf42..58ec9c56b67 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java @@ -183,6 +183,14 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf return camelize(sanitizeName(operationId)); } + public void addEnumIndexes(List> enumVars){ + int enumIndex = 0; + for (Map enumVar : enumVars) { + enumVar.put("protobuf-enum-index", enumIndex); + enumIndex++; + } + } + @Override public Map postProcessModels(Map objs) { objs = postProcessModelsEnum(objs); @@ -192,6 +200,14 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf Map mo = (Map) _mo; CodegenModel cm = (CodegenModel) mo.get("model"); + if(cm.isEnum) { + Map allowableValues = cm.getAllowableValues(); + if (allowableValues.containsKey("enumVars")) { + List> enumVars = (List>)allowableValues.get("enumVars"); + addEnumIndexes(enumVars); + } + } + for (CodegenProperty var : cm.vars) { // add x-protobuf-type: repeated if it's an array if (Boolean.TRUE.equals(var.isArray)) { @@ -209,12 +225,8 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf } if (var.isEnum && var.allowableValues.containsKey("enumVars")) { - List> enumVars = (List>) var.allowableValues.get("enumVars"); - int enumIndex = 0; - for (Map enumVar : enumVars) { - enumVar.put("protobuf-enum-index", enumIndex); - enumIndex++; - } + List> enumVars = (List>)var.allowableValues.get("enumVars"); + addEnumIndexes(enumVars); } // Add x-protobuf-index, unless already specified diff --git a/modules/openapi-generator/src/main/resources/protobuf-schema/enum.mustache b/modules/openapi-generator/src/main/resources/protobuf-schema/enum.mustache new file mode 100644 index 00000000000..aa26522c880 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/protobuf-schema/enum.mustache @@ -0,0 +1,7 @@ +enum {{classname}} { + {{#allowableValues}} + {{#enumVars}} + {{{name}}} = {{{protobuf-enum-index}}}; + {{/enumVars}} + {{/allowableValues}} +} diff --git a/modules/openapi-generator/src/main/resources/protobuf-schema/model.mustache b/modules/openapi-generator/src/main/resources/protobuf-schema/model.mustache index f16f097771d..2a609db9a8d 100644 --- a/modules/openapi-generator/src/main/resources/protobuf-schema/model.mustache +++ b/modules/openapi-generator/src/main/resources/protobuf-schema/model.mustache @@ -11,7 +11,7 @@ import public "{{{modelPackage}}}/{{{import}}}.proto"; {{#models}} {{#model}} -message {{classname}} { +{{#isEnum}}{{>enum}}{{/isEnum}}{{^isEnum}}message {{classname}} { {{#vars}} {{#description}} @@ -34,5 +34,6 @@ message {{classname}} { {{/vars}} } +{{/isEnum}} {{/model}} {{/models}} From c7bd3aa29473fb4f9e8f8dcca6ed32c0c5edbdff Mon Sep 17 00:00:00 2001 From: Felix Winterhalter Date: Mon, 22 Nov 2021 09:56:57 +0100 Subject: [PATCH 05/61] fix: Support Netcore 6.0 (#10634) --- docs/generators/csharp-netcore.md | 2 +- .../codegen/languages/CSharpNetCoreClientCodegen.java | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/generators/csharp-netcore.md b/docs/generators/csharp-netcore.md index 7a30e18f899..bb138ef414d 100644 --- a/docs/generators/csharp-netcore.md +++ b/docs/generators/csharp-netcore.md @@ -31,7 +31,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |src| -|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`|
**netstandard1.3**
.NET Standard 1.3 compatible
**netstandard1.4**
.NET Standard 1.4 compatible
**netstandard1.5**
.NET Standard 1.5 compatible
**netstandard1.6**
.NET Standard 1.6 compatible
**netstandard2.0**
.NET Standard 2.0 compatible
**netstandard2.1**
.NET Standard 2.1 compatible
**netcoreapp2.0**
.NET Core 2.0 compatible
**netcoreapp2.1**
.NET Core 2.1 compatible
**netcoreapp3.0**
.NET Core 3.0 compatible
**netcoreapp3.1**
.NET Core 3.1 compatible
**net47**
.NET Framework 4.7 compatible
**net5.0**
.NET 5.0 compatible
|netstandard2.0| +|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`|
**netstandard1.3**
.NET Standard 1.3 compatible
**netstandard1.4**
.NET Standard 1.4 compatible
**netstandard1.5**
.NET Standard 1.5 compatible
**netstandard1.6**
.NET Standard 1.6 compatible
**netstandard2.0**
.NET Standard 2.0 compatible
**netstandard2.1**
.NET Standard 2.1 compatible
**netcoreapp2.0**
.NET Core 2.0 compatible
**netcoreapp2.1**
.NET Core 2.1 compatible
**netcoreapp3.0**
.NET Core 3.0 compatible
**netcoreapp3.1**
.NET Core 3.1 compatible
**net47**
.NET Framework 4.7 compatible
**net5.0**
.NET 5.0 compatible
**net6.0**
.NET 6.0 compatible
|netstandard2.0| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java index b6e54b0fa21..1d6a13603f6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreClientCodegen.java @@ -70,7 +70,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { FrameworkStrategy.NETCOREAPP_3_0, FrameworkStrategy.NETCOREAPP_3_1, FrameworkStrategy.NETFRAMEWORK_4_7, - FrameworkStrategy.NET_5_0 + FrameworkStrategy.NET_5_0, + FrameworkStrategy.NET_6_0 ); private static FrameworkStrategy defaultFramework = FrameworkStrategy.NETSTANDARD_2_0; protected final Map frameworks; @@ -1001,6 +1002,8 @@ public class CSharpNetCoreClientCodegen extends AbstractCSharpCodegen { }; static FrameworkStrategy NET_5_0 = new FrameworkStrategy("net5.0", ".NET 5.0 compatible", "net5.0", Boolean.FALSE) { }; + static FrameworkStrategy NET_6_0 = new FrameworkStrategy("net6.0", ".NET 6.0 compatible", "net6.0", Boolean.FALSE) { + }; protected String name; protected String description; protected String testTargetFramework; From c13067d100c43cfbedea205df37f365014cbdb2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C4=8Cerm=C3=A1k?= Date: Mon, 22 Nov 2021 14:57:33 +0100 Subject: [PATCH 06/61] [Protobuf-Schema] Add unknown to enum switch (#10892) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [Protobuf-Schema] Add unknown to enum switch * [Protobuf-Schema] Bugfix: unique unknown by prefix * [Protobuf-Schema] Add unknown to enum switch * [Protobuf-Schema] Bugfix: unique unknown by prefix * [Protobuf-Schema] Bugfix after merge, format file * [Docs][Protobuf-Schema] Generated docs Co-authored-by: Tomáš Čermák --- docs/generators/protobuf-schema.md | 1 + .../languages/ProtobufSchemaCodegen.java | 43 +++++++++++++++++-- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/docs/generators/protobuf-schema.md b/docs/generators/protobuf-schema.md index 104a47fe59c..53e5334ef97 100644 --- a/docs/generators/protobuf-schema.md +++ b/docs/generators/protobuf-schema.md @@ -7,6 +7,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | +|startEnumsWithUnknown|Introduces "UNKNOWN" as the first element of enumerations.| |false| ## IMPORT MAPPING diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java index 58ec9c56b67..30a8b4c3c32 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java @@ -47,10 +47,14 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf private static final String IMPORTS = "imports"; + public static final String START_ENUMS_WITH_UNKNOWN = "startEnumsWithUnknown"; + private final Logger LOGGER = LoggerFactory.getLogger(ProtobufSchemaCodegen.class); protected String packageName = "openapitools"; + private boolean startEnumsWithUnknown = false; + @Override public CodegenType getTag() { return CodegenType.SCHEMA; @@ -145,6 +149,7 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf cliOptions.clear(); + addSwitch(START_ENUMS_WITH_UNKNOWN, "Introduces \"UNKNOWN\" as the first element of enumerations.", startEnumsWithUnknown); } @Override @@ -164,6 +169,10 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } + if (additionalProperties.containsKey(this.START_ENUMS_WITH_UNKNOWN)) { + this.startEnumsWithUnknown = convertPropertyToBooleanAndWriteBack(START_ENUMS_WITH_UNKNOWN); + } + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); } @@ -183,7 +192,27 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf return camelize(sanitizeName(operationId)); } - public void addEnumIndexes(List> enumVars){ + public void addUnknownToAllowableValues(Map allowableValues, String name) { + if(startEnumsWithUnknown) { + if(allowableValues.containsKey("enumVars")) { + List> enumVars = (List>)allowableValues.get("enumVars"); + + HashMap unknown = new HashMap(); + unknown.put("name", name + "_UNKNOWN"); + unknown.put("isString", "false"); + unknown.put("value", "\"" + name + "_UNKNOWN\""); + + enumVars.add(0, unknown); + } + + if(allowableValues.containsKey("values")) { + List values = (List)allowableValues.get("values"); + values.add(0, name + "_UNKNOWN"); + } + } + } + + public void addEnumIndexes(List> enumVars) { int enumIndex = 0; for (Map enumVar : enumVars) { enumVar.put("protobuf-enum-index", enumIndex); @@ -202,6 +231,8 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf if(cm.isEnum) { Map allowableValues = cm.getAllowableValues(); + addUnknownToAllowableValues(allowableValues, cm.getClassname()); + if (allowableValues.containsKey("enumVars")) { List> enumVars = (List>)allowableValues.get("enumVars"); addEnumIndexes(enumVars); @@ -224,9 +255,13 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf } } - if (var.isEnum && var.allowableValues.containsKey("enumVars")) { - List> enumVars = (List>)var.allowableValues.get("enumVars"); - addEnumIndexes(enumVars); + if (var.isEnum) { + addUnknownToAllowableValues(var.allowableValues, var.getEnumName()); + + if(var.allowableValues.containsKey("enumVars")) { + List> enumVars = (List>) var.allowableValues.get("enumVars"); + addEnumIndexes(enumVars); + } } // Add x-protobuf-index, unless already specified From e9f2ccde677e59402a46e957ac6169cfd8b05bcb Mon Sep 17 00:00:00 2001 From: Tomasz Prus Date: Mon, 22 Nov 2021 17:41:04 +0100 Subject: [PATCH 07/61] =?UTF-8?q?[Python]=20Add=20option=20to=20select=20c?= =?UTF-8?q?ontent-type=20using=20body=20or=20force=20it=20for=E2=80=A6=20(?= =?UTF-8?q?#10686)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [Python] Add option to select content-type using body or force it for API call * Add support for application/json-patch+json * Add unittests. --- .../main/resources/python-legacy/api.mustache | 10 +- .../python-legacy/api_client.mustache | 9 +- .../petstore_api/api/another_fake_api.py | 10 +- .../petstore_api/api/fake_api.py | 104 ++++++++---- .../api/fake_classname_tags_123_api.py | 10 +- .../petstore_api/api/pet_api.py | 66 +++++--- .../petstore_api/api/store_api.py | 16 +- .../petstore_api/api/user_api.py | 32 +++- .../python-asyncio/petstore_api/api_client.py | 9 +- .../petstore_api/api/another_fake_api.py | 10 +- .../petstore_api/api/fake_api.py | 104 ++++++++---- .../api/fake_classname_tags_123_api.py | 10 +- .../python-legacy/petstore_api/api/pet_api.py | 66 +++++--- .../petstore_api/api/store_api.py | 16 +- .../petstore_api/api/user_api.py | 32 +++- .../python-legacy/petstore_api/api_client.py | 9 +- .../python-legacy/tests/test_api_client.py | 10 ++ .../python-legacy/tests/test_pet_api.py | 22 +++ .../petstore_api/api/another_fake_api.py | 10 +- .../petstore_api/api/fake_api.py | 104 ++++++++---- .../api/fake_classname_tags_123_api.py | 10 +- .../petstore_api/api/pet_api.py | 66 +++++--- .../petstore_api/api/store_api.py | 16 +- .../petstore_api/api/user_api.py | 32 +++- .../python-tornado/petstore_api/api_client.py | 9 +- .../petstore_api/api/another_fake_api.py | 10 +- .../petstore_api/api/default_api.py | 4 +- .../petstore_api/api/fake_api.py | 152 ++++++++++++------ .../api/fake_classname_tags_123_api.py | 10 +- .../python-legacy/petstore_api/api/pet_api.py | 66 +++++--- .../petstore_api/api/store_api.py | 22 ++- .../petstore_api/api/user_api.py | 56 +++++-- .../python-legacy/petstore_api/api_client.py | 9 +- 33 files changed, 819 insertions(+), 302 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python-legacy/api.mustache b/modules/openapi-generator/src/main/resources/python-legacy/api.mustache index cca4ae9bd37..afde9560aa9 100644 --- a/modules/openapi-generator/src/main/resources/python-legacy/api.mustache +++ b/modules/openapi-generator/src/main/resources/python-legacy/api.mustache @@ -107,6 +107,7 @@ class {{classname}}(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -142,7 +143,8 @@ class {{classname}}(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -247,8 +249,10 @@ class {{classname}}(object): {{/hasProduces}} {{#hasConsumes}} # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - [{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}]) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + [{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}], + '{{httpMethod}}', body_params)) # noqa: E501 {{/hasConsumes}} # Authentication setting diff --git a/modules/openapi-generator/src/main/resources/python-legacy/api_client.mustache b/modules/openapi-generator/src/main/resources/python-legacy/api_client.mustache index daeb30ddc26..0bd33330262 100644 --- a/modules/openapi-generator/src/main/resources/python-legacy/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/python-legacy/api_client.mustache @@ -545,10 +545,12 @@ class ApiClient(object): else: return ', '.join(accepts) - def select_header_content_type(self, content_types): + def select_header_content_type(self, content_types, method=None, body=None): """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. + :param method: http method (e.g. POST, PATCH). + :param body: http body to send. :return: Content-Type (e.g. application/json). """ if not content_types: @@ -556,6 +558,11 @@ class ApiClient(object): content_types = [x.lower() for x in content_types] + if (method == 'PATCH' and + 'application/json-patch+json' in content_types and + isinstance(body, list)): + return 'application/json-patch+json' + if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: diff --git a/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py index b95df897b49..b76ee3b916c 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/another_fake_api.py @@ -95,6 +95,7 @@ class AnotherFakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class AnotherFakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -148,8 +150,10 @@ class AnotherFakeApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 diff --git a/samples/client/petstore/python-asyncio/petstore_api/api/fake_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/fake_api.py index 063ac8e08d1..b97f43f60f9 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/fake_api.py @@ -95,6 +95,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -144,8 +146,10 @@ class FakeApi(object): if 'xml_item' in local_var_params: body_params = local_var_params['xml_item'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/xml', 'application/xml; charset=utf-8', 'application/xml; charset=utf-16', 'text/xml', 'text/xml; charset=utf-8', 'text/xml; charset=utf-16']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/xml', 'application/xml; charset=utf-8', 'application/xml; charset=utf-16', 'text/xml', 'text/xml; charset=utf-8', 'text/xml; charset=utf-16'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -228,6 +232,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -245,7 +250,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -359,6 +365,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -376,7 +383,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -490,6 +498,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -507,7 +516,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -621,6 +631,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -638,7 +649,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -752,6 +764,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -769,7 +782,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -801,8 +815,10 @@ class FakeApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -887,6 +903,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -905,7 +922,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -943,8 +961,10 @@ class FakeApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1027,6 +1047,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1044,7 +1065,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1080,8 +1102,10 @@ class FakeApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1218,6 +1242,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1248,7 +1273,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1346,8 +1372,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['http_basic_test'] # noqa: E501 @@ -1458,6 +1486,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1482,7 +1511,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1527,8 +1557,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'GET', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1631,6 +1663,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1653,7 +1686,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1781,6 +1815,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1798,7 +1833,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1830,8 +1866,10 @@ class FakeApi(object): if 'param' in local_var_params: body_params = local_var_params['param'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1916,6 +1954,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1934,7 +1973,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1972,8 +2012,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'GET', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -2072,6 +2114,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -2093,7 +2136,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/client/petstore/python-asyncio/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/fake_classname_tags_123_api.py index 5d6405e2cbd..2b46147fed5 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/fake_classname_tags_123_api.py @@ -95,6 +95,7 @@ class FakeClassnameTags123Api(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class FakeClassnameTags123Api(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -148,8 +150,10 @@ class FakeClassnameTags123Api(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = ['api_key_query'] # noqa: E501 diff --git a/samples/client/petstore/python-asyncio/petstore_api/api/pet_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/pet_api.py index 50dab4563e9..e20e57a7f86 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/pet_api.py @@ -93,6 +93,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -110,7 +111,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -142,8 +144,10 @@ class PetApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json', 'application/xml']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json', 'application/xml'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -228,6 +232,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -246,7 +251,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -360,6 +366,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -377,7 +384,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -497,6 +505,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -514,7 +523,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -634,6 +644,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -651,7 +662,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -769,6 +781,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -786,7 +799,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -818,8 +832,10 @@ class PetApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json', 'application/xml']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json', 'application/xml'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -908,6 +924,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -927,7 +944,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -963,8 +981,10 @@ class PetApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -1053,6 +1073,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1072,7 +1093,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1112,8 +1134,10 @@ class PetApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['multipart/form-data']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -1204,6 +1228,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1223,7 +1248,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1267,8 +1293,10 @@ class PetApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['multipart/form-data']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 diff --git a/samples/client/petstore/python-asyncio/petstore_api/api/store_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/store_api.py index 092a4542774..4425692aec0 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/api/store_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/store_api.py @@ -95,6 +95,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -220,6 +222,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -236,7 +239,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -348,6 +352,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -365,7 +370,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -487,6 +493,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -504,7 +511,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/client/petstore/python-asyncio/petstore_api/api/user_api.py b/samples/client/petstore/python-asyncio/petstore_api/api/user_api.py index 7c68a89e624..593e5e5856b 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/api/user_api.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api/user_api.py @@ -95,6 +95,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -222,6 +224,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -239,7 +242,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -349,6 +353,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -366,7 +371,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -478,6 +484,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -495,7 +502,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -605,6 +613,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -622,7 +631,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -744,6 +754,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -762,7 +773,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -881,6 +893,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -897,7 +910,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1007,6 +1021,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1025,7 +1040,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/client/petstore/python-asyncio/petstore_api/api_client.py b/samples/client/petstore/python-asyncio/petstore_api/api_client.py index 4e718812e55..122a18d0cab 100644 --- a/samples/client/petstore/python-asyncio/petstore_api/api_client.py +++ b/samples/client/petstore/python-asyncio/petstore_api/api_client.py @@ -522,10 +522,12 @@ class ApiClient(object): else: return ', '.join(accepts) - def select_header_content_type(self, content_types): + def select_header_content_type(self, content_types, method=None, body=None): """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. + :param method: http method (e.g. POST, PATCH). + :param body: http body to send. :return: Content-Type (e.g. application/json). """ if not content_types: @@ -533,6 +535,11 @@ class ApiClient(object): content_types = [x.lower() for x in content_types] + if (method == 'PATCH' and + 'application/json-patch+json' in content_types and + isinstance(body, list)): + return 'application/json-patch+json' + if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: diff --git a/samples/client/petstore/python-legacy/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-legacy/petstore_api/api/another_fake_api.py index b95df897b49..b76ee3b916c 100644 --- a/samples/client/petstore/python-legacy/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-legacy/petstore_api/api/another_fake_api.py @@ -95,6 +95,7 @@ class AnotherFakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class AnotherFakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -148,8 +150,10 @@ class AnotherFakeApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 diff --git a/samples/client/petstore/python-legacy/petstore_api/api/fake_api.py b/samples/client/petstore/python-legacy/petstore_api/api/fake_api.py index 063ac8e08d1..b97f43f60f9 100644 --- a/samples/client/petstore/python-legacy/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python-legacy/petstore_api/api/fake_api.py @@ -95,6 +95,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -144,8 +146,10 @@ class FakeApi(object): if 'xml_item' in local_var_params: body_params = local_var_params['xml_item'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/xml', 'application/xml; charset=utf-8', 'application/xml; charset=utf-16', 'text/xml', 'text/xml; charset=utf-8', 'text/xml; charset=utf-16']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/xml', 'application/xml; charset=utf-8', 'application/xml; charset=utf-16', 'text/xml', 'text/xml; charset=utf-8', 'text/xml; charset=utf-16'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -228,6 +232,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -245,7 +250,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -359,6 +365,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -376,7 +383,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -490,6 +498,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -507,7 +516,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -621,6 +631,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -638,7 +649,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -752,6 +764,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -769,7 +782,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -801,8 +815,10 @@ class FakeApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -887,6 +903,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -905,7 +922,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -943,8 +961,10 @@ class FakeApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1027,6 +1047,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1044,7 +1065,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1080,8 +1102,10 @@ class FakeApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1218,6 +1242,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1248,7 +1273,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1346,8 +1372,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['http_basic_test'] # noqa: E501 @@ -1458,6 +1486,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1482,7 +1511,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1527,8 +1557,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'GET', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1631,6 +1663,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1653,7 +1686,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1781,6 +1815,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1798,7 +1833,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1830,8 +1866,10 @@ class FakeApi(object): if 'param' in local_var_params: body_params = local_var_params['param'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1916,6 +1954,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1934,7 +1973,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1972,8 +2012,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'GET', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -2072,6 +2114,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -2093,7 +2136,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/client/petstore/python-legacy/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-legacy/petstore_api/api/fake_classname_tags_123_api.py index 5d6405e2cbd..2b46147fed5 100644 --- a/samples/client/petstore/python-legacy/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-legacy/petstore_api/api/fake_classname_tags_123_api.py @@ -95,6 +95,7 @@ class FakeClassnameTags123Api(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class FakeClassnameTags123Api(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -148,8 +150,10 @@ class FakeClassnameTags123Api(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = ['api_key_query'] # noqa: E501 diff --git a/samples/client/petstore/python-legacy/petstore_api/api/pet_api.py b/samples/client/petstore/python-legacy/petstore_api/api/pet_api.py index 50dab4563e9..e20e57a7f86 100644 --- a/samples/client/petstore/python-legacy/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python-legacy/petstore_api/api/pet_api.py @@ -93,6 +93,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -110,7 +111,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -142,8 +144,10 @@ class PetApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json', 'application/xml']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json', 'application/xml'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -228,6 +232,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -246,7 +251,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -360,6 +366,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -377,7 +384,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -497,6 +505,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -514,7 +523,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -634,6 +644,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -651,7 +662,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -769,6 +781,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -786,7 +799,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -818,8 +832,10 @@ class PetApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json', 'application/xml']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json', 'application/xml'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -908,6 +924,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -927,7 +944,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -963,8 +981,10 @@ class PetApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -1053,6 +1073,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1072,7 +1093,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1112,8 +1134,10 @@ class PetApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['multipart/form-data']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -1204,6 +1228,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1223,7 +1248,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1267,8 +1293,10 @@ class PetApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['multipart/form-data']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 diff --git a/samples/client/petstore/python-legacy/petstore_api/api/store_api.py b/samples/client/petstore/python-legacy/petstore_api/api/store_api.py index 092a4542774..4425692aec0 100644 --- a/samples/client/petstore/python-legacy/petstore_api/api/store_api.py +++ b/samples/client/petstore/python-legacy/petstore_api/api/store_api.py @@ -95,6 +95,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -220,6 +222,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -236,7 +239,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -348,6 +352,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -365,7 +370,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -487,6 +493,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -504,7 +511,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/client/petstore/python-legacy/petstore_api/api/user_api.py b/samples/client/petstore/python-legacy/petstore_api/api/user_api.py index 7c68a89e624..593e5e5856b 100644 --- a/samples/client/petstore/python-legacy/petstore_api/api/user_api.py +++ b/samples/client/petstore/python-legacy/petstore_api/api/user_api.py @@ -95,6 +95,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -222,6 +224,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -239,7 +242,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -349,6 +353,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -366,7 +371,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -478,6 +484,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -495,7 +502,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -605,6 +613,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -622,7 +631,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -744,6 +754,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -762,7 +773,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -881,6 +893,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -897,7 +910,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1007,6 +1021,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1025,7 +1040,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/client/petstore/python-legacy/petstore_api/api_client.py b/samples/client/petstore/python-legacy/petstore_api/api_client.py index 7c3a69abd76..15464e6282b 100644 --- a/samples/client/petstore/python-legacy/petstore_api/api_client.py +++ b/samples/client/petstore/python-legacy/petstore_api/api_client.py @@ -521,10 +521,12 @@ class ApiClient(object): else: return ', '.join(accepts) - def select_header_content_type(self, content_types): + def select_header_content_type(self, content_types, method=None, body=None): """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. + :param method: http method (e.g. POST, PATCH). + :param body: http body to send. :return: Content-Type (e.g. application/json). """ if not content_types: @@ -532,6 +534,11 @@ class ApiClient(object): content_types = [x.lower() for x in content_types] + if (method == 'PATCH' and + 'application/json-patch+json' in content_types and + isinstance(body, list)): + return 'application/json-patch+json' + if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: diff --git a/samples/client/petstore/python-legacy/tests/test_api_client.py b/samples/client/petstore/python-legacy/tests/test_api_client.py index 216e1f9ec1b..8da54be7ae7 100644 --- a/samples/client/petstore/python-legacy/tests/test_api_client.py +++ b/samples/client/petstore/python-legacy/tests/test_api_client.py @@ -98,6 +98,16 @@ class ApiClientTests(unittest.TestCase): content_type = self.api_client.select_header_content_type(content_types) self.assertEqual(content_type, 'application/json') + content_types = ['application/json-patch+json', 'application/json'] + content_type = self.api_client.select_header_content_type(content_types, + 'PATCH', [{ "op": "add", "path": "/myPath", "value": ["myValue"]}]) + self.assertEqual(content_type, 'application/json-patch+json') + + content_types = ['application/json-patch+json', 'application/json'] + content_type = self.api_client.select_header_content_type(content_types, + 'PATCH', {"value": ["myValue"]}) + self.assertEqual(content_type, 'application/json') + def test_sanitize_for_serialization(self): # None data = None diff --git a/samples/client/petstore/python-legacy/tests/test_pet_api.py b/samples/client/petstore/python-legacy/tests/test_pet_api.py index a7b47bdc567..4e894436d4b 100644 --- a/samples/client/petstore/python-legacy/tests/test_pet_api.py +++ b/samples/client/petstore/python-legacy/tests/test_pet_api.py @@ -13,6 +13,7 @@ $ nosetests -v import os import unittest +from unittest.mock import patch import petstore_api from petstore_api import Configuration @@ -293,5 +294,26 @@ class PetApiTests(unittest.TestCase): except ApiException as e: self.assertEqual(404, e.status) + @patch.object(petstore_api.ApiClient, 'call_api') + @patch.object(petstore_api.ApiClient, 'select_header_content_type') + def test_call_select_header_content_type(self, mock_select_ct, mock_call_api): + mock_select_ct.return_value = 'application/json' + self.pet_api.add_pet({'id': 1000, 'name': 'my pet'}) + mock_select_ct.assert_called_once_with( + ['application/json', 'application/xml'], + 'POST', + {'id': 1000, 'name': 'my pet'}) + mock_call_api.assert_called_once() + self.assertEqual(mock_call_api.mock_calls[0][1][4], + {'Content-Type': 'application/json'}) + + @patch.object(petstore_api.ApiClient, 'call_api') + def test_call_with_forced_content_type(self, mock_call_api): + mock_call_api.return_value = 'application/xml' + self.pet_api.add_pet('', _content_type='application/xml') + mock_call_api.assert_called_once() + self.assertEqual(mock_call_api.mock_calls[0][1][4], + {'Content-Type': 'application/xml'}) + if __name__ == '__main__': unittest.main() diff --git a/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py b/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py index b95df897b49..b76ee3b916c 100644 --- a/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/another_fake_api.py @@ -95,6 +95,7 @@ class AnotherFakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class AnotherFakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -148,8 +150,10 @@ class AnotherFakeApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 diff --git a/samples/client/petstore/python-tornado/petstore_api/api/fake_api.py b/samples/client/petstore/python-tornado/petstore_api/api/fake_api.py index 063ac8e08d1..b97f43f60f9 100644 --- a/samples/client/petstore/python-tornado/petstore_api/api/fake_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/fake_api.py @@ -95,6 +95,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -144,8 +146,10 @@ class FakeApi(object): if 'xml_item' in local_var_params: body_params = local_var_params['xml_item'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/xml', 'application/xml; charset=utf-8', 'application/xml; charset=utf-16', 'text/xml', 'text/xml; charset=utf-8', 'text/xml; charset=utf-16']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/xml', 'application/xml; charset=utf-8', 'application/xml; charset=utf-16', 'text/xml', 'text/xml; charset=utf-8', 'text/xml; charset=utf-16'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -228,6 +232,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -245,7 +250,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -359,6 +365,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -376,7 +383,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -490,6 +498,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -507,7 +516,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -621,6 +631,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -638,7 +649,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -752,6 +764,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -769,7 +782,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -801,8 +815,10 @@ class FakeApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -887,6 +903,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -905,7 +922,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -943,8 +961,10 @@ class FakeApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1027,6 +1047,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1044,7 +1065,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1080,8 +1102,10 @@ class FakeApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1218,6 +1242,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1248,7 +1273,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1346,8 +1372,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['http_basic_test'] # noqa: E501 @@ -1458,6 +1486,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1482,7 +1511,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1527,8 +1557,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'GET', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1631,6 +1663,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1653,7 +1686,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1781,6 +1815,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1798,7 +1833,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1830,8 +1866,10 @@ class FakeApi(object): if 'param' in local_var_params: body_params = local_var_params['param'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1916,6 +1954,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1934,7 +1973,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1972,8 +2012,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'GET', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -2072,6 +2114,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -2093,7 +2136,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/client/petstore/python-tornado/petstore_api/api/fake_classname_tags_123_api.py b/samples/client/petstore/python-tornado/petstore_api/api/fake_classname_tags_123_api.py index 5d6405e2cbd..2b46147fed5 100644 --- a/samples/client/petstore/python-tornado/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/fake_classname_tags_123_api.py @@ -95,6 +95,7 @@ class FakeClassnameTags123Api(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class FakeClassnameTags123Api(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -148,8 +150,10 @@ class FakeClassnameTags123Api(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = ['api_key_query'] # noqa: E501 diff --git a/samples/client/petstore/python-tornado/petstore_api/api/pet_api.py b/samples/client/petstore/python-tornado/petstore_api/api/pet_api.py index 50dab4563e9..e20e57a7f86 100644 --- a/samples/client/petstore/python-tornado/petstore_api/api/pet_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/pet_api.py @@ -93,6 +93,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -110,7 +111,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -142,8 +144,10 @@ class PetApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json', 'application/xml']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json', 'application/xml'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -228,6 +232,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -246,7 +251,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -360,6 +366,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -377,7 +384,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -497,6 +505,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -514,7 +523,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -634,6 +644,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -651,7 +662,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -769,6 +781,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -786,7 +799,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -818,8 +832,10 @@ class PetApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json', 'application/xml']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json', 'application/xml'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -908,6 +924,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -927,7 +944,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -963,8 +981,10 @@ class PetApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -1053,6 +1073,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1072,7 +1093,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1112,8 +1134,10 @@ class PetApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['multipart/form-data']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -1204,6 +1228,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1223,7 +1248,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1267,8 +1293,10 @@ class PetApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['multipart/form-data']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 diff --git a/samples/client/petstore/python-tornado/petstore_api/api/store_api.py b/samples/client/petstore/python-tornado/petstore_api/api/store_api.py index 092a4542774..4425692aec0 100644 --- a/samples/client/petstore/python-tornado/petstore_api/api/store_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/store_api.py @@ -95,6 +95,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -220,6 +222,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -236,7 +239,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -348,6 +352,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -365,7 +370,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -487,6 +493,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -504,7 +511,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/client/petstore/python-tornado/petstore_api/api/user_api.py b/samples/client/petstore/python-tornado/petstore_api/api/user_api.py index 7c68a89e624..593e5e5856b 100644 --- a/samples/client/petstore/python-tornado/petstore_api/api/user_api.py +++ b/samples/client/petstore/python-tornado/petstore_api/api/user_api.py @@ -95,6 +95,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -222,6 +224,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -239,7 +242,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -349,6 +353,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -366,7 +371,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -478,6 +484,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -495,7 +502,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -605,6 +613,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -622,7 +631,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -744,6 +754,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -762,7 +773,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -881,6 +893,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -897,7 +910,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1007,6 +1021,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1025,7 +1040,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/client/petstore/python-tornado/petstore_api/api_client.py b/samples/client/petstore/python-tornado/petstore_api/api_client.py index 8c41c345d57..5a833ebd1c0 100644 --- a/samples/client/petstore/python-tornado/petstore_api/api_client.py +++ b/samples/client/petstore/python-tornado/petstore_api/api_client.py @@ -523,10 +523,12 @@ class ApiClient(object): else: return ', '.join(accepts) - def select_header_content_type(self, content_types): + def select_header_content_type(self, content_types, method=None, body=None): """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. + :param method: http method (e.g. POST, PATCH). + :param body: http body to send. :return: Content-Type (e.g. application/json). """ if not content_types: @@ -534,6 +536,11 @@ class ApiClient(object): content_types = [x.lower() for x in content_types] + if (method == 'PATCH' and + 'application/json-patch+json' in content_types and + isinstance(body, list)): + return 'application/json-patch+json' + if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/another_fake_api.py index 7dad5ca84ae..43e5339dcc9 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/another_fake_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/another_fake_api.py @@ -95,6 +95,7 @@ class AnotherFakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class AnotherFakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -148,8 +150,10 @@ class AnotherFakeApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/default_api.py index 7f2691f7cf5..d3be5ae092a 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/default_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/default_api.py @@ -89,6 +89,7 @@ class DefaultApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -105,7 +106,8 @@ class DefaultApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py index 7de994ea565..a08aee25453 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_api.py @@ -89,6 +89,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -105,7 +106,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -223,6 +225,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -242,7 +245,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -278,8 +282,10 @@ class FakeApi(object): if 'pet' in local_var_params: body_params = local_var_params['pet'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json', 'application/xml']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json', 'application/xml'], + 'GET', body_params)) # noqa: E501 # Authentication setting auth_settings = ['http_signature_test'] # noqa: E501 @@ -362,6 +368,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -379,7 +386,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -411,8 +419,10 @@ class FakeApi(object): ['*/*']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -497,6 +507,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -514,7 +525,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -546,8 +558,10 @@ class FakeApi(object): ['*/*']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -632,6 +646,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -649,7 +664,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -681,8 +697,10 @@ class FakeApi(object): ['*/*']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -767,6 +785,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -784,7 +803,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -816,8 +836,10 @@ class FakeApi(object): ['*/*']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -902,6 +924,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -919,7 +942,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -955,8 +979,10 @@ class FakeApi(object): ['*/*']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1041,6 +1067,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1058,7 +1085,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1086,8 +1114,10 @@ class FakeApi(object): if 'body' in local_var_params: body_params = local_var_params['body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['image/png']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['image/png'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1170,6 +1200,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1187,7 +1218,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1219,8 +1251,10 @@ class FakeApi(object): if 'file_schema_test_class' in local_var_params: body_params = local_var_params['file_schema_test_class'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1305,6 +1339,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1323,7 +1358,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1361,8 +1397,10 @@ class FakeApi(object): if 'user' in local_var_params: body_params = local_var_params['user'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1445,6 +1483,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1462,7 +1501,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1498,8 +1538,10 @@ class FakeApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -1636,6 +1678,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1666,7 +1709,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1764,8 +1808,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['http_basic_test'] # noqa: E501 @@ -1876,6 +1922,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1900,7 +1947,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1945,8 +1993,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'GET', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -2049,6 +2099,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -2071,7 +2122,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -2199,6 +2251,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -2216,7 +2269,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -2248,8 +2302,10 @@ class FakeApi(object): if 'request_body' in local_var_params: body_params = local_var_params['request_body'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -2334,6 +2390,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -2352,7 +2409,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -2390,8 +2448,10 @@ class FakeApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'GET', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -2498,6 +2558,7 @@ class FakeApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -2521,7 +2582,8 @@ class FakeApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_classname_tags_123_api.py index dffc78620e9..1dd90624e71 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_classname_tags_123_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/fake_classname_tags_123_api.py @@ -95,6 +95,7 @@ class FakeClassnameTags123Api(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class FakeClassnameTags123Api(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -148,8 +150,10 @@ class FakeClassnameTags123Api(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PATCH', body_params)) # noqa: E501 # Authentication setting auth_settings = ['api_key_query'] # noqa: E501 diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/pet_api.py index a4195ecad3e..5f4bcb8888b 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/pet_api.py @@ -93,6 +93,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -123,7 +124,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -155,8 +157,10 @@ class PetApi(object): if 'pet' in local_var_params: body_params = local_var_params['pet'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json', 'application/xml']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json', 'application/xml'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -242,6 +246,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -260,7 +265,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -374,6 +380,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -391,7 +398,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -511,6 +519,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -528,7 +537,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -648,6 +658,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -665,7 +676,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -783,6 +795,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -813,7 +826,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -845,8 +859,10 @@ class PetApi(object): if 'pet' in local_var_params: body_params = local_var_params['pet'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json', 'application/xml']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json', 'application/xml'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -936,6 +952,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -955,7 +972,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -991,8 +1009,10 @@ class PetApi(object): body_params = None # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/x-www-form-urlencoded']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/x-www-form-urlencoded'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -1081,6 +1101,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1100,7 +1121,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1140,8 +1162,10 @@ class PetApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['multipart/form-data']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 @@ -1232,6 +1256,7 @@ class PetApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1251,7 +1276,8 @@ class PetApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1295,8 +1321,10 @@ class PetApi(object): ['application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['multipart/form-data']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = ['petstore_auth'] # noqa: E501 diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/store_api.py index 0d6c2fdf6b7..48c85b36d7b 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/store_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/store_api.py @@ -95,6 +95,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -220,6 +222,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -236,7 +239,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -348,6 +352,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -365,7 +370,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -487,6 +493,7 @@ class StoreApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -504,7 +511,8 @@ class StoreApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -540,8 +548,10 @@ class StoreApi(object): ['application/xml', 'application/json']) # noqa: E501 # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/user_api.py index 8e4f70e6c7a..89fd46adef9 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api/user_api.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api/user_api.py @@ -95,6 +95,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -112,7 +113,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -144,8 +146,10 @@ class UserApi(object): if 'user' in local_var_params: body_params = local_var_params['user'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -226,6 +230,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -243,7 +248,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -275,8 +281,10 @@ class UserApi(object): if 'user' in local_var_params: body_params = local_var_params['user'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -357,6 +365,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -374,7 +383,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -406,8 +416,10 @@ class UserApi(object): if 'user' in local_var_params: body_params = local_var_params['user'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'POST', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 @@ -490,6 +502,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -507,7 +520,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -617,6 +631,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -634,7 +649,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -756,6 +772,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -774,7 +791,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -893,6 +911,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -909,7 +928,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1019,6 +1039,7 @@ class UserApi(object): request; this effectively ignores the authentication in the spec for a single request. :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request :return: Returns the result object. If the method is called asynchronously, returns the request thread. @@ -1037,7 +1058,8 @@ class UserApi(object): '_return_http_data_only', '_preload_content', '_request_timeout', - '_request_auth' + '_request_auth', + '_content_type' ] ) @@ -1075,8 +1097,10 @@ class UserApi(object): if 'user' in local_var_params: body_params = local_var_params['user'] # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['application/json']) # noqa: E501 + header_params['Content-Type'] = local_var_params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'], + 'PUT', body_params)) # noqa: E501 # Authentication setting auth_settings = [] # noqa: E501 diff --git a/samples/openapi3/client/petstore/python-legacy/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-legacy/petstore_api/api_client.py index 7c3a69abd76..15464e6282b 100755 --- a/samples/openapi3/client/petstore/python-legacy/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python-legacy/petstore_api/api_client.py @@ -521,10 +521,12 @@ class ApiClient(object): else: return ', '.join(accepts) - def select_header_content_type(self, content_types): + def select_header_content_type(self, content_types, method=None, body=None): """Returns `Content-Type` based on an array of content_types provided. :param content_types: List of content-types. + :param method: http method (e.g. POST, PATCH). + :param body: http body to send. :return: Content-Type (e.g. application/json). """ if not content_types: @@ -532,6 +534,11 @@ class ApiClient(object): content_types = [x.lower() for x in content_types] + if (method == 'PATCH' and + 'application/json-patch+json' in content_types and + isinstance(body, list)): + return 'application/json-patch+json' + if 'application/json' in content_types or '*/*' in content_types: return 'application/json' else: From 49e9911b3ffd6e0730e04a3bdbbb29e100b03c8a Mon Sep 17 00:00:00 2001 From: Jens L Date: Mon, 22 Nov 2021 22:17:15 +0100 Subject: [PATCH 08/61] [typescript-fetch] fix circular imports being generated (#10798) templates based off of #6140 and @ajaska closes #6140 --- .../resources/typescript-fetch/modelGeneric.mustache | 6 +++--- .../main/resources/typescript-fetch/modelOneOf.mustache | 9 ++++----- .../builds/default-v3.0/models/ArrayTest.ts | 2 +- .../typescript-fetch/builds/default-v3.0/models/Cat.ts | 4 +++- .../typescript-fetch/builds/default-v3.0/models/Dog.ts | 4 +++- .../builds/default-v3.0/models/EnumTest.ts | 8 +++++++- .../builds/default-v3.0/models/FormatTest.ts | 2 +- .../builds/default-v3.0/models/InlineResponseDefault.ts | 2 +- .../MixedPropertiesAndAdditionalPropertiesClass.ts | 2 +- .../default-v3.0/models/ObjectWithDeprecatedFields.ts | 2 +- .../default-v3.0/models/OuterObjectWithEnumProperty.ts | 2 +- .../typescript-fetch/builds/default-v3.0/models/Pet.ts | 4 +++- .../typescript-fetch/builds/default/models/Pet.ts | 4 +++- .../builds/enum/models/EnumPatternObject.ts | 4 +++- .../typescript-fetch/builds/es6-target/src/models/Pet.ts | 4 +++- .../builds/multiple-parameters/models/Pet.ts | 4 +++- .../builds/prefix-parameter-interfaces/src/models/Pet.ts | 4 +++- .../src/models/DefaultMetaOnlyResponse.ts | 2 +- .../src/models/FindPetsByStatusResponse.ts | 4 +++- .../src/models/FindPetsByUserResponse.ts | 4 +++- .../src/models/GetBehaviorPermissionsResponse.ts | 2 +- .../src/models/GetBehaviorTypeResponse.ts | 4 +++- .../src/models/GetMatchingPartsResponse.ts | 4 +++- .../src/models/GetPetPartTypeResponse.ts | 4 +++- .../builds/sagas-and-records/src/models/MatchingParts.ts | 2 +- .../builds/sagas-and-records/src/models/ModelError.ts | 2 +- .../builds/sagas-and-records/src/models/Pet.ts | 8 +++++++- .../sagas-and-records/src/models/PetRegionsResponse.ts | 2 +- .../builds/sagas-and-records/src/models/ResponseMeta.ts | 2 +- .../builds/typescript-three-plus/src/models/Pet.ts | 4 +++- .../builds/with-interfaces/models/Pet.ts | 4 +++- .../builds/with-npm-version/src/models/Pet.ts | 4 +++- 32 files changed, 81 insertions(+), 38 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache index 1428b031f5a..b37cfdec9da 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGeneric.mustache @@ -1,13 +1,13 @@ import { exists, mapValues } from '../runtime'; {{#hasImports}} +{{#imports}} import { - {{#imports}} {{{.}}}, {{.}}FromJSON, {{.}}FromJSONTyped, {{.}}ToJSON, - {{/imports}} -} from './'; +} from './{{.}}'; +{{/imports}} {{/hasImports}} {{#discriminator}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache index 12d60088b42..7cb97abeba8 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache @@ -1,13 +1,12 @@ {{#hasImports}} +{{#oneOf}} import { - {{#imports}} {{{.}}}, - {{/imports}} - {{#oneOf}} + {{{.}}}FromJSON, {{{.}}}FromJSONTyped, {{{.}}}ToJSON, - {{/oneOf}} -} from './'; +} from './{{.}}'; +{{/oneOf}} {{/hasImports}} {{>modelOneOfInterfaces}} diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/ArrayTest.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/ArrayTest.ts index e4c5f1e0c5b..17144b78281 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/ArrayTest.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/ArrayTest.ts @@ -18,7 +18,7 @@ import { ReadOnlyFirstFromJSON, ReadOnlyFirstFromJSONTyped, ReadOnlyFirstToJSON, -} from './'; +} from './ReadOnlyFirst'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Cat.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Cat.ts index 9ca592b7f45..7d6db07958a 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Cat.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Cat.ts @@ -18,11 +18,13 @@ import { AnimalFromJSON, AnimalFromJSONTyped, AnimalToJSON, +} from './Animal'; +import { CatAllOf, CatAllOfFromJSON, CatAllOfFromJSONTyped, CatAllOfToJSON, -} from './'; +} from './CatAllOf'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Dog.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Dog.ts index 2194d53d12f..f68b8e02510 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Dog.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Dog.ts @@ -18,11 +18,13 @@ import { AnimalFromJSON, AnimalFromJSONTyped, AnimalToJSON, +} from './Animal'; +import { DogAllOf, DogAllOfFromJSON, DogAllOfFromJSONTyped, DogAllOfToJSON, -} from './'; +} from './DogAllOf'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/EnumTest.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/EnumTest.ts index 0dad062d603..22e369f3986 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/EnumTest.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/EnumTest.ts @@ -18,19 +18,25 @@ import { OuterEnumFromJSON, OuterEnumFromJSONTyped, OuterEnumToJSON, +} from './OuterEnum'; +import { OuterEnumDefaultValue, OuterEnumDefaultValueFromJSON, OuterEnumDefaultValueFromJSONTyped, OuterEnumDefaultValueToJSON, +} from './OuterEnumDefaultValue'; +import { OuterEnumInteger, OuterEnumIntegerFromJSON, OuterEnumIntegerFromJSONTyped, OuterEnumIntegerToJSON, +} from './OuterEnumInteger'; +import { OuterEnumIntegerDefaultValue, OuterEnumIntegerDefaultValueFromJSON, OuterEnumIntegerDefaultValueFromJSONTyped, OuterEnumIntegerDefaultValueToJSON, -} from './'; +} from './OuterEnumIntegerDefaultValue'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/FormatTest.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/FormatTest.ts index dc076e5ed75..b60fcb5756a 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/FormatTest.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/FormatTest.ts @@ -18,7 +18,7 @@ import { DecimalFromJSON, DecimalFromJSONTyped, DecimalToJSON, -} from './'; +} from './Decimal'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/InlineResponseDefault.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/InlineResponseDefault.ts index 572379f86a4..adcfc15dfbd 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/InlineResponseDefault.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/InlineResponseDefault.ts @@ -18,7 +18,7 @@ import { FooFromJSON, FooFromJSONTyped, FooToJSON, -} from './'; +} from './Foo'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/MixedPropertiesAndAdditionalPropertiesClass.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/MixedPropertiesAndAdditionalPropertiesClass.ts index ebb07fd89cb..15e830ea39c 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/MixedPropertiesAndAdditionalPropertiesClass.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/MixedPropertiesAndAdditionalPropertiesClass.ts @@ -18,7 +18,7 @@ import { AnimalFromJSON, AnimalFromJSONTyped, AnimalToJSON, -} from './'; +} from './Animal'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/ObjectWithDeprecatedFields.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/ObjectWithDeprecatedFields.ts index 6fa59dbfca8..c14eb976bfa 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/ObjectWithDeprecatedFields.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/ObjectWithDeprecatedFields.ts @@ -18,7 +18,7 @@ import { DeprecatedObjectFromJSON, DeprecatedObjectFromJSONTyped, DeprecatedObjectToJSON, -} from './'; +} from './DeprecatedObject'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/OuterObjectWithEnumProperty.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/OuterObjectWithEnumProperty.ts index 7e638d06292..878aef40cdf 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/OuterObjectWithEnumProperty.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/OuterObjectWithEnumProperty.ts @@ -18,7 +18,7 @@ import { OuterEnumIntegerFromJSON, OuterEnumIntegerFromJSONTyped, OuterEnumIntegerToJSON, -} from './'; +} from './OuterEnumInteger'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Pet.ts index fc8cdac4329..4b88dc214eb 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Pet.ts @@ -18,11 +18,13 @@ import { CategoryFromJSON, CategoryFromJSONTyped, CategoryToJSON, +} from './Category'; +import { Tag, TagFromJSON, TagFromJSONTyped, TagToJSON, -} from './'; +} from './Tag'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/default/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/default/models/Pet.ts index 9417338414a..6a75faae426 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/models/Pet.ts @@ -18,11 +18,13 @@ import { CategoryFromJSON, CategoryFromJSONTyped, CategoryToJSON, +} from './Category'; +import { Tag, TagFromJSON, TagFromJSONTyped, TagToJSON, -} from './'; +} from './Tag'; /** * A pet for sale in the pet store diff --git a/samples/client/petstore/typescript-fetch/builds/enum/models/EnumPatternObject.ts b/samples/client/petstore/typescript-fetch/builds/enum/models/EnumPatternObject.ts index e8fc617e08d..463eadb6d55 100644 --- a/samples/client/petstore/typescript-fetch/builds/enum/models/EnumPatternObject.ts +++ b/samples/client/petstore/typescript-fetch/builds/enum/models/EnumPatternObject.ts @@ -18,11 +18,13 @@ import { NumberEnumFromJSON, NumberEnumFromJSONTyped, NumberEnumToJSON, +} from './NumberEnum'; +import { StringEnum, StringEnumFromJSON, StringEnumFromJSONTyped, StringEnumToJSON, -} from './'; +} from './StringEnum'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Pet.ts index 9417338414a..6a75faae426 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/src/models/Pet.ts @@ -18,11 +18,13 @@ import { CategoryFromJSON, CategoryFromJSONTyped, CategoryToJSON, +} from './Category'; +import { Tag, TagFromJSON, TagFromJSONTyped, TagToJSON, -} from './'; +} from './Tag'; /** * A pet for sale in the pet store diff --git a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Pet.ts index 9417338414a..6a75faae426 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/models/Pet.ts @@ -18,11 +18,13 @@ import { CategoryFromJSON, CategoryFromJSONTyped, CategoryToJSON, +} from './Category'; +import { Tag, TagFromJSON, TagFromJSONTyped, TagToJSON, -} from './'; +} from './Tag'; /** * A pet for sale in the pet store diff --git a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Pet.ts index 9417338414a..6a75faae426 100644 --- a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/models/Pet.ts @@ -18,11 +18,13 @@ import { CategoryFromJSON, CategoryFromJSONTyped, CategoryToJSON, +} from './Category'; +import { Tag, TagFromJSON, TagFromJSONTyped, TagToJSON, -} from './'; +} from './Tag'; /** * A pet for sale in the pet store diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts index b7fda0a183e..5b4dc83e5fe 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/DefaultMetaOnlyResponse.ts @@ -18,7 +18,7 @@ import { ResponseMetaFromJSON, ResponseMetaFromJSONTyped, ResponseMetaToJSON, -} from './'; +} from './ResponseMeta'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts index 9562ca6e87c..28dd4020cd8 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByStatusResponse.ts @@ -18,11 +18,13 @@ import { PetFromJSON, PetFromJSONTyped, PetToJSON, +} from './Pet'; +import { ResponseMeta, ResponseMetaFromJSON, ResponseMetaFromJSONTyped, ResponseMetaToJSON, -} from './'; +} from './ResponseMeta'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts index 42c2da380fa..4b767465168 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/FindPetsByUserResponse.ts @@ -18,11 +18,13 @@ import { ResponseMetaFromJSON, ResponseMetaFromJSONTyped, ResponseMetaToJSON, +} from './ResponseMeta'; +import { User, UserFromJSON, UserFromJSONTyped, UserToJSON, -} from './'; +} from './User'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts index b011c2c69a7..a53838a7464 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorPermissionsResponse.ts @@ -18,7 +18,7 @@ import { ResponseMetaFromJSON, ResponseMetaFromJSONTyped, ResponseMetaToJSON, -} from './'; +} from './ResponseMeta'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts index 924639ae196..c770b29beb7 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetBehaviorTypeResponse.ts @@ -18,11 +18,13 @@ import { BehaviorTypeFromJSON, BehaviorTypeFromJSONTyped, BehaviorTypeToJSON, +} from './BehaviorType'; +import { ResponseMeta, ResponseMetaFromJSON, ResponseMetaFromJSONTyped, ResponseMetaToJSON, -} from './'; +} from './ResponseMeta'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts index 76174ef6fcd..3690c3954f1 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetMatchingPartsResponse.ts @@ -18,11 +18,13 @@ import { MatchingPartsFromJSON, MatchingPartsFromJSONTyped, MatchingPartsToJSON, +} from './MatchingParts'; +import { ResponseMeta, ResponseMetaFromJSON, ResponseMetaFromJSONTyped, ResponseMetaToJSON, -} from './'; +} from './ResponseMeta'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts index d7a28113741..9a70cdc1a69 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/GetPetPartTypeResponse.ts @@ -18,11 +18,13 @@ import { PetPartTypeFromJSON, PetPartTypeFromJSONTyped, PetPartTypeToJSON, +} from './PetPartType'; +import { ResponseMeta, ResponseMetaFromJSON, ResponseMetaFromJSONTyped, ResponseMetaToJSON, -} from './'; +} from './ResponseMeta'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts index 7cd3d6c3352..70177cf458c 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/MatchingParts.ts @@ -18,7 +18,7 @@ import { PartFromJSON, PartFromJSONTyped, PartToJSON, -} from './'; +} from './Part'; /** * Contains all the matching parts diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts index 8e509add65c..7a4c5b62d03 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ModelError.ts @@ -18,7 +18,7 @@ import { ItemIdFromJSON, ItemIdFromJSONTyped, ItemIdToJSON, -} from './'; +} from './ItemId'; /** * This represent an error normally linked to a specific item from a previous request diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts index 2b59b900171..26e07c36c0f 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/Pet.ts @@ -18,19 +18,25 @@ import { CategoryFromJSON, CategoryFromJSONTyped, CategoryToJSON, +} from './Category'; +import { DeploymentRequestStatus, DeploymentRequestStatusFromJSON, DeploymentRequestStatusFromJSONTyped, DeploymentRequestStatusToJSON, +} from './DeploymentRequestStatus'; +import { Tag, TagFromJSON, TagFromJSONTyped, TagToJSON, +} from './Tag'; +import { WarningCode, WarningCodeFromJSON, WarningCodeFromJSONTyped, WarningCodeToJSON, -} from './'; +} from './WarningCode'; /** * A pet for sale in the pet store diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRegionsResponse.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRegionsResponse.ts index 7b4c268864d..2a2c7fb6a51 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRegionsResponse.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRegionsResponse.ts @@ -18,7 +18,7 @@ import { ResponseMetaFromJSON, ResponseMetaFromJSONTyped, ResponseMetaToJSON, -} from './'; +} from './ResponseMeta'; /** * diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts index 38fdca904cf..8c84dd4b556 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/ResponseMeta.ts @@ -18,7 +18,7 @@ import { ErrorCodeFromJSON, ErrorCodeFromJSONTyped, ErrorCodeToJSON, -} from './'; +} from './ErrorCode'; /** * Mandatory part of each response given by our API diff --git a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Pet.ts index 9417338414a..6a75faae426 100644 --- a/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/typescript-three-plus/src/models/Pet.ts @@ -18,11 +18,13 @@ import { CategoryFromJSON, CategoryFromJSONTyped, CategoryToJSON, +} from './Category'; +import { Tag, TagFromJSON, TagFromJSONTyped, TagToJSON, -} from './'; +} from './Tag'; /** * A pet for sale in the pet store diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Pet.ts index 9417338414a..6a75faae426 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/models/Pet.ts @@ -18,11 +18,13 @@ import { CategoryFromJSON, CategoryFromJSONTyped, CategoryToJSON, +} from './Category'; +import { Tag, TagFromJSON, TagFromJSONTyped, TagToJSON, -} from './'; +} from './Tag'; /** * A pet for sale in the pet store diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Pet.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Pet.ts index 9417338414a..6a75faae426 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Pet.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/models/Pet.ts @@ -18,11 +18,13 @@ import { CategoryFromJSON, CategoryFromJSONTyped, CategoryToJSON, +} from './Category'; +import { Tag, TagFromJSON, TagFromJSONTyped, TagToJSON, -} from './'; +} from './Tag'; /** * A pet for sale in the pet store From e5159ef8d5a7f39777eaefe5d7fc0c4c83f79c6e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C4=8Cerm=C3=A1k?= Date: Tue, 23 Nov 2021 03:43:34 +0100 Subject: [PATCH 09/61] [Protobuf-Schema] Add numbered field number list switch (#10893) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * [Protobuf-Schema] Add numbered field number list switch * [Protobuf-Schema] Add numbered field number list switch * [Protobuf-Schema] Added switch * [Docs][Protobuf-Schema] Generated docs Co-authored-by: Tomáš Čermák --- docs/generators/protobuf-schema.md | 1 + .../languages/ProtobufSchemaCodegen.java | 26 +++++++++++++++---- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/docs/generators/protobuf-schema.md b/docs/generators/protobuf-schema.md index 53e5334ef97..a7d1f1d095b 100644 --- a/docs/generators/protobuf-schema.md +++ b/docs/generators/protobuf-schema.md @@ -7,6 +7,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl | Option | Description | Values | Default | | ------ | ----------- | ------ | ------- | +|numberedFieldNumberList|Field numbers in order.| |false| |startEnumsWithUnknown|Introduces "UNKNOWN" as the first element of enumerations.| |false| ## IMPORT MAPPING diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java index 30a8b4c3c32..5f55e9d47f0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ProtobufSchemaCodegen.java @@ -47,12 +47,16 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf private static final String IMPORTS = "imports"; + public static final String NUMBERED_FIELD_NUMBER_LIST = "numberedFieldNumberList"; + public static final String START_ENUMS_WITH_UNKNOWN = "startEnumsWithUnknown"; private final Logger LOGGER = LoggerFactory.getLogger(ProtobufSchemaCodegen.class); protected String packageName = "openapitools"; + private boolean numberedFieldNumberList = false; + private boolean startEnumsWithUnknown = false; @Override @@ -149,6 +153,7 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf cliOptions.clear(); + addSwitch(NUMBERED_FIELD_NUMBER_LIST, "Field numbers in order.", numberedFieldNumberList); addSwitch(START_ENUMS_WITH_UNKNOWN, "Introduces \"UNKNOWN\" as the first element of enumerations.", startEnumsWithUnknown); } @@ -169,6 +174,10 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf setPackageName((String) additionalProperties.get(CodegenConstants.PACKAGE_NAME)); } + if (additionalProperties.containsKey(this.NUMBERED_FIELD_NUMBER_LIST)) { + this.numberedFieldNumberList = convertPropertyToBooleanAndWriteBack(NUMBERED_FIELD_NUMBER_LIST); + } + if (additionalProperties.containsKey(this.START_ENUMS_WITH_UNKNOWN)) { this.startEnumsWithUnknown = convertPropertyToBooleanAndWriteBack(START_ENUMS_WITH_UNKNOWN); } @@ -239,6 +248,7 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf } } + int index = 1; for (CodegenProperty var : cm.vars) { // add x-protobuf-type: repeated if it's an array if (Boolean.TRUE.equals(var.isArray)) { @@ -265,11 +275,17 @@ public class ProtobufSchemaCodegen extends DefaultCodegen implements CodegenConf } // Add x-protobuf-index, unless already specified - try { - var.vendorExtensions.putIfAbsent("x-protobuf-index", generateFieldNumberFromString(var.getName())); - } catch (ProtoBufIndexComputationException e) { - LOGGER.error("Exception when assigning a index to a protobuf field", e); - var.vendorExtensions.putIfAbsent("x-protobuf-index", "Generated field number is in reserved range (19000, 19999)"); + if(this.numberedFieldNumberList) { + var.vendorExtensions.putIfAbsent("x-protobuf-index", index); + index++; + } + else { + try { + var.vendorExtensions.putIfAbsent("x-protobuf-index", generateFieldNumberFromString(var.getName())); + } catch (ProtoBufIndexComputationException e) { + LOGGER.error("Exception when assigning a index to a protobuf field", e); + var.vendorExtensions.putIfAbsent("x-protobuf-index", "Generated field number is in reserved range (19000, 19999)"); + } } } } From 39b8f83e6de3209c6d0619fd4259af591323e386 Mon Sep 17 00:00:00 2001 From: Tal Kirshboim Date: Tue, 23 Nov 2021 14:01:17 +0100 Subject: [PATCH 10/61] Add Airthings to list of generator users (#10936) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5774c216447..8aca24c1a67 100644 --- a/README.md +++ b/README.md @@ -577,6 +577,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [Adaptant Solutions AG](https://www.adaptant.io/) - [adesso SE](https://www.adesso.de/) - [Agoda](https://www.agoda.com/) +- [Airthings](https://www.airthings.com/) - [Allianz](https://www.allianz.com) - [Angular.Schule](https://angular.schule/) - [Aqovia](https://aqovia.com/) From 8338962debb123faca81aedfc29b134b644a45f1 Mon Sep 17 00:00:00 2001 From: cyangle Date: Tue, 23 Nov 2021 07:02:49 -0600 Subject: [PATCH 11/61] [crystal] Add annotation to reserved key word list of crystal lang (#10932) * add annotation to reserved key word list of crystal * Update crystal docs --- docs/generators/crystal.md | 1 + .../openapitools/codegen/languages/CrystalClientCodegen.java | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/generators/crystal.md b/docs/generators/crystal.md index 721384c810c..93a893215ca 100644 --- a/docs/generators/crystal.md +++ b/docs/generators/crystal.md @@ -58,6 +58,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • abstract
  • alias
  • +
  • annotation
  • as
  • as?
  • asm
  • diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java index 0ff2d657e7a..2e77181d7a3 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CrystalClientCodegen.java @@ -132,7 +132,7 @@ public class CrystalClientCodegen extends DefaultCodegen { // reserved word. Ref: https://github.com/crystal-lang/crystal/wiki/Crystal-for-Rubyists#available-keywords reservedWords = new HashSet<>( Arrays.asList( - "abstract", "do", "if", "nil?", "select", "union", + "abstract", "annotation", "do", "if", "nil?", "select", "union", "alias", "else", "in", "of", "self", "unless", "as", "elsif", "include", "out", "sizeof", "until", "as?", "end", "instance", "sizeof", "pointerof", "struct", "verbatim", From 3a12b6144f605eb3c206fdc3fcbf879ce8f5d701 Mon Sep 17 00:00:00 2001 From: Tal Kirshboim Date: Tue, 23 Nov 2021 14:04:43 +0100 Subject: [PATCH 12/61] Fix enum generation (#10923) --- .../src/main/resources/kotlin-client/enum_class.mustache | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache index 3548914cd0a..57b1e5f1272 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache @@ -22,7 +22,7 @@ import kotlinx.serialization.* * * Values: {{#allowableValues}}{{#enumVars}}{{&name}}{{^-last}},{{/-last}}{{/enumVars}}{{/allowableValues}} */ -{{#multiplatform}}@Serializable(with = {{classname}}.Serializer::class){{/multiplatform}}{{#kotlinx_serialization}}@Serializable{{/kotlinx_serialization}} +{{#multiplatform}}@Serializable{{/multiplatform}}{{#kotlinx_serialization}}@Serializable{{/kotlinx_serialization}} {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{classname}}(val value: {{{dataType}}}) { {{#allowableValues}}{{#enumVars}} {{^multiplatform}} From faae00df91f24ad4e3b8ad58f6a7052cd7811417 Mon Sep 17 00:00:00 2001 From: Fumito Nakazawa Date: Tue, 23 Nov 2021 22:18:42 +0900 Subject: [PATCH 13/61] [swift5] Refactor some codes (#10937) * Use compactMap * Remove as Any cast * Remove array * Update samples --- .../main/resources/swift5/APIHelper.mustache | 25 +++++++++++++++---- .../main/resources/swift5/Extensions.mustache | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- .../Sources/PetstoreClient/APIHelper.swift | 25 +++++++++++++++---- .../Sources/PetstoreClient/Extensions.swift | 20 +++++++-------- .../Classes/OpenAPIs/APIHelper.swift | 25 +++++++++++++++---- .../Classes/OpenAPIs/Extensions.swift | 20 +++++++-------- 30 files changed, 450 insertions(+), 225 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache b/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache index e535c7df4c4..78c98979b9c 100644 --- a/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/APIHelper.mustache @@ -24,7 +24,12 @@ import Vapor{{/useVapor}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -48,7 +53,12 @@ import Vapor{{/useVapor}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -56,9 +66,14 @@ import Vapor{{/useVapor}} {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache index 7f5d8b582f7..b286fa9f42a 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache @@ -12,15 +12,15 @@ import PromiseKit{{/usePromiseKit}}{{#useVapor}} import Vapor{{/useVapor}}{{^useVapor}} extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -32,22 +32,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -69,7 +69,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -81,7 +81,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -185,7 +185,7 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } }{{/useVapor}}{{#usePromiseKit}} diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index 5d8f35bff49..83d36bb6434 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ internal struct APIHelper { internal static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ internal struct APIHelper { internal static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ internal struct APIHelper { internal static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 65ae1c6c642..63647fe3703 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 68c3c6ee7e4..2c1ceeb385b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -11,15 +11,15 @@ import AnyCodable import PromiseKit extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -31,22 +31,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -68,7 +68,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -80,7 +80,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -184,7 +184,7 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index dc0913d093f..4077c82552a 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -97,6 +97,6 @@ extension UUID: JSONEncodable { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift index f7bb5274bd9..049b7f655f1 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -23,7 +23,12 @@ public struct APIHelper { public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { return source.reduce(into: [String: String]()) { result, item in if let collection = item.value as? [Any?] { - result[item.key] = collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } else if let value: Any = item.value { result[item.key] = "\(value)" } @@ -47,7 +52,12 @@ public struct APIHelper { public static func mapValueToPathItem(_ source: Any) -> Any { if let collection = source as? [Any?] { - return collection.filter { $0 != nil }.map { "\($0!)" }.joined(separator: ",") + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") } return source } @@ -55,9 +65,14 @@ public struct APIHelper { public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in if let collection = item.value as? [Any?] { - collection.filter { $0 != nil }.map { "\($0!)" }.forEach { value in - result.append(URLQueryItem(name: item.key, value: value)) - } + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } } else if let value = item.value { result.append(URLQueryItem(name: item.key, value: "\(value)")) } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift index e23035dde30..5831422f09d 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,15 +10,15 @@ import AnyCodable #endif extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension Int32: JSONEncodable { @@ -30,22 +30,22 @@ extension Int64: JSONEncodable { } extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension String: JSONEncodable { - func encodeToJSON() -> Any { return self as Any } + func encodeToJSON() -> Any { return self } } extension RawRepresentable where RawValue: JSONEncodable { - func encodeToJSON() -> Any { return self.rawValue as Any } + func encodeToJSON() -> Any { return self.rawValue } } private func encodeIfPossible(_ object: T) -> Any { if let encodableObject = object as? JSONEncodable { return encodableObject.encodeToJSON() } else { - return object as Any + return object } } @@ -67,7 +67,7 @@ extension Dictionary: JSONEncodable { for (key, value) in self { dictionary[key] = encodeIfPossible(value) } - return dictionary as Any + return dictionary } } @@ -79,7 +79,7 @@ extension Data: JSONEncodable { extension Date: JSONEncodable { func encodeToJSON() -> Any { - return CodableHelper.dateFormatter.string(from: self) as Any + return CodableHelper.dateFormatter.string(from: self) } } @@ -183,6 +183,6 @@ extension KeyedDecodingContainerProtocol { extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { - return Array(200 ..< 300).contains(statusCode) + return (200 ..< 300).contains(statusCode) } } From 64a478a93c1163f816634acb81a1e35283ed71f1 Mon Sep 17 00:00:00 2001 From: Fumito Nakazawa Date: Tue, 23 Nov 2021 22:18:56 +0900 Subject: [PATCH 14/61] [swift5] Remove optional from body (#10938) * Unwrap body * Remove unsupported type from nonDecodableBuilder * Update samples * Remove ! * Fix typo --- .../src/main/resources/swift5/Models.mustache | 6 +- .../src/main/resources/swift5/api.mustache | 10 +- .../AlamofireImplementations.mustache | 92 ++----------------- .../URLSessionImplementations.mustache | 60 ++---------- .../OpenAPIs/AlamofireImplementations.swift | 92 ++----------------- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/APIs/AnotherFakeAPI.swift | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 10 +- .../APIs/FakeClassnameTags123API.swift | 2 +- .../Classes/OpenAPIs/APIs/PetAPI.swift | 10 +- .../Classes/OpenAPIs/APIs/StoreAPI.swift | 6 +- .../Classes/OpenAPIs/APIs/UserAPI.swift | 4 +- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../OpenAPIs/APIs/AnotherFakeAPI.swift | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 10 +- .../APIs/FakeClassnameTags123API.swift | 2 +- .../Classes/OpenAPIs/APIs/PetAPI.swift | 10 +- .../Classes/OpenAPIs/APIs/StoreAPI.swift | 6 +- .../Classes/OpenAPIs/APIs/UserAPI.swift | 4 +- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../OpenAPIs/APIs/AnotherFakeAPI.swift | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 10 +- .../APIs/FakeClassnameTags123API.swift | 2 +- .../Classes/OpenAPIs/APIs/PetAPI.swift | 10 +- .../Classes/OpenAPIs/APIs/StoreAPI.swift | 6 +- .../Classes/OpenAPIs/APIs/UserAPI.swift | 4 +- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../OpenAPIs/APIs/AnotherFakeAPI.swift | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 10 +- .../APIs/FakeClassnameTags123API.swift | 2 +- .../Classes/OpenAPIs/APIs/PetAPI.swift | 10 +- .../Classes/OpenAPIs/APIs/StoreAPI.swift | 6 +- .../Classes/OpenAPIs/APIs/UserAPI.swift | 4 +- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../OpenAPIs/APIs/AnotherFakeAPI.swift | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 10 +- .../APIs/FakeClassnameTags123API.swift | 2 +- .../Classes/OpenAPIs/APIs/PetAPI.swift | 10 +- .../Classes/OpenAPIs/APIs/StoreAPI.swift | 6 +- .../Classes/OpenAPIs/APIs/UserAPI.swift | 4 +- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- .../Sources/PetstoreClient/Models.swift | 6 +- .../URLSessionImplementations.swift | 60 ++---------- .../Classes/OpenAPIs/Models.swift | 6 +- .../OpenAPIs/URLSessionImplementations.swift | 60 ++---------- 62 files changed, 231 insertions(+), 1063 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/swift5/Models.mustache b/modules/openapi-generator/src/main/resources/swift5/Models.mustache index 74ce973b287..e8ca64cdc52 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Models.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Models.mustache @@ -33,15 +33,15 @@ protocol JSONEncodable { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class Response { {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let statusCode: Int {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let header: [String: String] - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let body: T? + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} let body: T - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(statusCode: Int, header: [String: String], body: T?) { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} convenience init(response: HTTPURLResponse, body: T?) { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/modules/openapi-generator/src/main/resources/swift5/api.mustache b/modules/openapi-generator/src/main/resources/swift5/api.mustache index d0b300c64c1..6e95e653a32 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api.mustache @@ -97,7 +97,7 @@ extension {{projectName}}API { switch result { {{#returnType}} case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) {{/returnType}} {{^returnType}} case .success: @@ -128,7 +128,7 @@ extension {{projectName}}API { switch result { {{#returnType}} case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) {{/returnType}} {{^returnType}} case .success: @@ -167,7 +167,7 @@ extension {{projectName}}API { switch result { {{#returnType}} case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) {{/returnType}} {{^returnType}} case .success: @@ -212,7 +212,7 @@ extension {{projectName}}API { switch result { {{#returnType}} case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) {{/returnType}} {{^returnType}} case .success: @@ -246,7 +246,7 @@ extension {{projectName}}API { switch result { {{#returnType}} case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) {{/returnType}} {{^returnType}} case .success: diff --git a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache index 31446b09543..48105ef58d9 100644 --- a/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/libraries/alamofire/AlamofireImplementations.mustache @@ -160,100 +160,20 @@ private var managerStore = SynchronizedDictionary() let validatedRequest = request.validate() switch T.self { - case is String.Type: - validatedRequest.responseString(queue: apiResponseQueue, completionHandler: { stringResponse in - cleanupRequest() - - switch stringResponse.result { - case let .success(value): - completion(.success(Response(response: stringResponse.response!, body: value as? T))) - case let .failure(error): - completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.response, error))) - } - - }) - case is URL.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in - cleanupRequest() - - do { - - guard case .success = dataResponse.result else { - throw DownloadException.responseFailed - } - - guard let data = dataResponse.data else { - throw DownloadException.responseDataMissing - } - - guard let request = request.request else { - throw DownloadException.requestMissing - } - - let fileManager = FileManager.default - let urlRequest = try request.asURLRequest() - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try self.getURL(from: urlRequest) - - var requestPath = try self.getPath(from: requestURL) - - if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.{{projectName}}.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: dataResponse.response!, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, error))) - } - return - }) case is Void.Type: validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { voidResponse in cleanupRequest() switch voidResponse.result { case .success: - completion(.success(Response(response: voidResponse.response!, body: nil))) + completion(.success(Response(response: voidResponse.response!, body: () as! T))) case let .failure(error): completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) } - }) - case is Data.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in - cleanupRequest() - - switch dataResponse.result { - case .success: - completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) - case let .failure(error): - completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) - } - }) default: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in - cleanupRequest() - - switch dataResponse.result { - case .success: - completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) - case let .failure(error): - completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) - } - - }) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -338,7 +258,7 @@ private var managerStore = SynchronizedDictionary() switch stringResponse.result { case let .success(value): - completion(.success(Response(response: stringResponse.response!, body: value as? T))) + completion(.success(Response(response: stringResponse.response!, body: value as! T))) case let .failure(error): completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.response, error))) } @@ -381,7 +301,7 @@ private var managerStore = SynchronizedDictionary() try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: dataResponse.response!, body: filePath as? T))) + completion(.success(Response(response: dataResponse.response!, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError))) @@ -396,7 +316,7 @@ private var managerStore = SynchronizedDictionary() switch voidResponse.result { case .success: - completion(.success(Response(response: voidResponse.response!, body: nil))) + completion(.success(Response(response: voidResponse.response!, body: () as! T))) case let .failure(error): completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) } @@ -408,7 +328,7 @@ private var managerStore = SynchronizedDictionary() switch dataResponse.result { case .success: - completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) + completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as! T))) case let .failure(error): completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) } diff --git a/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache b/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache index 648556996ca..707577e0da3 100644 --- a/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache @@ -200,60 +200,12 @@ private var credentialStore = SynchronizedDictionary() } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.{{projectName}}.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ private var credentialStore = SynchronizedDictionary() let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ private var credentialStore = SynchronizedDictionary() try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ private var credentialStore = SynchronizedDictionary() case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift index 5fe5eaa7bec..c8f1b663434 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/AlamofireImplementations.swift @@ -160,100 +160,20 @@ open class AlamofireRequestBuilder: RequestBuilder { let validatedRequest = request.validate() switch T.self { - case is String.Type: - validatedRequest.responseString(queue: apiResponseQueue, completionHandler: { stringResponse in - cleanupRequest() - - switch stringResponse.result { - case let .success(value): - completion(.success(Response(response: stringResponse.response!, body: value as? T))) - case let .failure(error): - completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.response, error))) - } - - }) - case is URL.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in - cleanupRequest() - - do { - - guard case .success = dataResponse.result else { - throw DownloadException.responseFailed - } - - guard let data = dataResponse.data else { - throw DownloadException.responseDataMissing - } - - guard let request = request.request else { - throw DownloadException.requestMissing - } - - let fileManager = FileManager.default - let urlRequest = try request.asURLRequest() - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try self.getURL(from: urlRequest) - - var requestPath = try self.getPath(from: requestURL) - - if let headerFileName = self.getFileName(fromContentDisposition: dataResponse.response?.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: dataResponse.response!, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, error))) - } - return - }) case is Void.Type: validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { voidResponse in cleanupRequest() switch voidResponse.result { case .success: - completion(.success(Response(response: voidResponse.response!, body: nil))) + completion(.success(Response(response: voidResponse.response!, body: () as! T))) case let .failure(error): completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) } - }) - case is Data.Type: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in - cleanupRequest() - - switch dataResponse.result { - case .success: - completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) - case let .failure(error): - completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) - } - }) default: - validatedRequest.responseData(queue: apiResponseQueue, completionHandler: { dataResponse in - cleanupRequest() - - switch dataResponse.result { - case .success: - completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) - case let .failure(error): - completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) - } - - }) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -338,7 +258,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild switch stringResponse.result { case let .success(value): - completion(.success(Response(response: stringResponse.response!, body: value as? T))) + completion(.success(Response(response: stringResponse.response!, body: value as! T))) case let .failure(error): completion(.failure(ErrorResponse.error(stringResponse.response?.statusCode ?? 500, stringResponse.data, stringResponse.response, error))) } @@ -381,7 +301,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: dataResponse.response!, body: filePath as? T))) + completion(.success(Response(response: dataResponse.response!, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, dataResponse.data, dataResponse.response, requestParserError))) @@ -396,7 +316,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild switch voidResponse.result { case .success: - completion(.success(Response(response: voidResponse.response!, body: nil))) + completion(.success(Response(response: voidResponse.response!, body: () as! T))) case let .failure(error): completion(.failure(ErrorResponse.error(voidResponse.response?.statusCode ?? 500, voidResponse.data, voidResponse.response, error))) } @@ -408,7 +328,7 @@ open class AlamofireDecodableRequestBuilder: AlamofireRequestBuild switch dataResponse.result { case .success: - completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as? T))) + completion(.success(Response(response: dataResponse.response!, body: dataResponse.data as! T))) case let .failure(error): completion(.failure(ErrorResponse.error(dataResponse.response?.statusCode ?? 500, dataResponse.data, dataResponse.response, error))) } diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 45ca9d14c10..4877906db16 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -33,7 +33,7 @@ open class AnotherFakeAPI { task = call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 50aa3c4f2dd..e773584bb02 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -32,7 +32,7 @@ open class FakeAPI { task = fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -87,7 +87,7 @@ open class FakeAPI { task = fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -142,7 +142,7 @@ open class FakeAPI { task = fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -197,7 +197,7 @@ open class FakeAPI { task = fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -367,7 +367,7 @@ open class FakeAPI { task = testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 5bb42aa3465..66d801132d2 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -33,7 +33,7 @@ open class FakeClassnameTags123API { task = testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 8bc53adc9c0..2f713417bfb 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -165,7 +165,7 @@ open class PetAPI { task = findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -229,7 +229,7 @@ open class PetAPI { task = findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -293,7 +293,7 @@ open class PetAPI { task = getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -489,7 +489,7 @@ open class PetAPI { task = uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -561,7 +561,7 @@ open class PetAPI { task = uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 6cfed59b37a..41d3a6047dc 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -92,7 +92,7 @@ open class StoreAPI { task = getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -151,7 +151,7 @@ open class StoreAPI { task = getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -211,7 +211,7 @@ open class StoreAPI { task = placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 48b052e3fcf..f0e57f333cd 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -262,7 +262,7 @@ open class UserAPI { task = getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } @@ -322,7 +322,7 @@ open class UserAPI { task = loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in switch result { case let .success(response): - continuation.resume(returning: response.body!) + continuation.resume(returning: response.body) case let .failure(error): continuation.resume(throwing: error) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 6b18892fd71..724845424e6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -30,7 +30,7 @@ open class AnotherFakeAPI { task = call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 57e4aee7b36..b64f5581ea6 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -29,7 +29,7 @@ open class FakeAPI { task = fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -80,7 +80,7 @@ open class FakeAPI { task = fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -131,7 +131,7 @@ open class FakeAPI { task = fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -182,7 +182,7 @@ open class FakeAPI { task = fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -340,7 +340,7 @@ open class FakeAPI { task = testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 963f5b9ff8d..f9538610472 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -30,7 +30,7 @@ open class FakeClassnameTags123API { task = testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index aea9263a7a5..1335065e013 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -154,7 +154,7 @@ open class PetAPI { task = findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -214,7 +214,7 @@ open class PetAPI { task = findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -274,7 +274,7 @@ open class PetAPI { task = getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -458,7 +458,7 @@ open class PetAPI { task = uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -526,7 +526,7 @@ open class PetAPI { task = uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index e4a71a69dfd..ec3368c105a 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -85,7 +85,7 @@ open class StoreAPI { task = getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -140,7 +140,7 @@ open class StoreAPI { task = getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -196,7 +196,7 @@ open class StoreAPI { task = placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 79cce70e949..5ec63243c52 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -243,7 +243,7 @@ open class UserAPI { task = getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } @@ -299,7 +299,7 @@ open class UserAPI { task = loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in switch result { case let .success(response): - promise(.success(response.body!)) + promise(.success(response.body)) case let .failure(error): promise(.failure(error)) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift index f372f83aac8..5db24390bd7 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ internal enum DecodableRequestBuilderError: Error { internal class Response { internal let statusCode: Int internal let header: [String: String] - internal let body: T? + internal let body: T - internal init(statusCode: Int, header: [String: String], body: T?) { + internal init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - internal convenience init(response: HTTPURLResponse, body: T?) { + internal convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 3046f05e3cd..0d4c11bc1ac 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ internal class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ internal class URLSessionDecodableRequestBuilder: URLSessionReques let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ internal class URLSessionDecodableRequestBuilder: URLSessionReques try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ internal class URLSessionDecodableRequestBuilder: URLSessionReques case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 75fd284604e..2e86e0cbaa4 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -25,7 +25,7 @@ open class AnotherFakeAPI { call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 3009dcc5901..ef784bfffdc 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -24,7 +24,7 @@ open class FakeAPI { fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -67,7 +67,7 @@ open class FakeAPI { fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -110,7 +110,7 @@ open class FakeAPI { fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -153,7 +153,7 @@ open class FakeAPI { fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -287,7 +287,7 @@ open class FakeAPI { testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 1a81a5cc681..84cc164d5bf 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -25,7 +25,7 @@ open class FakeClassnameTags123API { testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5545eb0b7ac..a6de43f3870 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -133,7 +133,7 @@ open class PetAPI { findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -185,7 +185,7 @@ open class PetAPI { findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -237,7 +237,7 @@ open class PetAPI { getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -397,7 +397,7 @@ open class PetAPI { uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -457,7 +457,7 @@ open class PetAPI { uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index af27df36ea4..dba4582cb83 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -72,7 +72,7 @@ open class StoreAPI { getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -119,7 +119,7 @@ open class StoreAPI { getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -167,7 +167,7 @@ open class StoreAPI { placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 76e6ed4d0b3..0053bffff2b 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -206,7 +206,7 @@ open class UserAPI { getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } @@ -254,7 +254,7 @@ open class UserAPI { loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in switch result { case let .success(response): - deferred.resolver.fulfill(response.body!) + deferred.resolver.fulfill(response.body) case let .failure(error): deferred.resolver.reject(error) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 1277c034392..03e84c9a2e3 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -24,7 +24,7 @@ open class AnotherFakeAPI { return call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 2b796b1fd2f..1bb864f1684 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -23,7 +23,7 @@ open class FakeAPI { return fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -65,7 +65,7 @@ open class FakeAPI { return fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -107,7 +107,7 @@ open class FakeAPI { return fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -149,7 +149,7 @@ open class FakeAPI { return fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -280,7 +280,7 @@ open class FakeAPI { return testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 30d24c9a9e3..0749c5c9dc7 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -24,7 +24,7 @@ open class FakeClassnameTags123API { return testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index a381d52b651..ff5d3c3db10 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -130,7 +130,7 @@ open class PetAPI { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -181,7 +181,7 @@ open class PetAPI { return findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -232,7 +232,7 @@ open class PetAPI { return getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -389,7 +389,7 @@ open class PetAPI { return uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -448,7 +448,7 @@ open class PetAPI { return uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 66824247d0d..6ce5440ab90 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -70,7 +70,7 @@ open class StoreAPI { return getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -116,7 +116,7 @@ open class StoreAPI { return getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -163,7 +163,7 @@ open class StoreAPI { return placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 799e257924d..bca3f08fe83 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -201,7 +201,7 @@ open class UserAPI { return getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } @@ -248,7 +248,7 @@ open class UserAPI { return loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in switch result { case let .success(response): - completion(.success(response.body!)) + completion(.success(response.body)) case let .failure(error): completion(.failure(error)) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index bc8aa33bf49..34db22eeb11 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -25,7 +25,7 @@ open class AnotherFakeAPI { let task = call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 2873a26ba83..7836542dbe0 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -24,7 +24,7 @@ open class FakeAPI { let task = fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -72,7 +72,7 @@ open class FakeAPI { let task = fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -120,7 +120,7 @@ open class FakeAPI { let task = fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -168,7 +168,7 @@ open class FakeAPI { let task = fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -317,7 +317,7 @@ open class FakeAPI { let task = testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index cffcafcba69..a19dd70dd44 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -25,7 +25,7 @@ open class FakeClassnameTags123API { let task = testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 95d0a84b169..1f346ba1019 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -143,7 +143,7 @@ open class PetAPI { let task = findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -200,7 +200,7 @@ open class PetAPI { let task = findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -257,7 +257,7 @@ open class PetAPI { let task = getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -432,7 +432,7 @@ open class PetAPI { let task = uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -497,7 +497,7 @@ open class PetAPI { let task = uploadFileWithRequiredFileWithRequestBuilder(petId: petId, requiredFile: requiredFile, additionalMetadata: additionalMetadata).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index 829ebefaa98..09ef3615620 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -77,7 +77,7 @@ open class StoreAPI { let task = getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -129,7 +129,7 @@ open class StoreAPI { let task = getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -182,7 +182,7 @@ open class StoreAPI { let task = placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index f00d31a838b..be932ce5e32 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -226,7 +226,7 @@ open class UserAPI { let task = getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } @@ -279,7 +279,7 @@ open class UserAPI { let task = loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in switch result { case let .success(response): - observer.onNext(response.body!) + observer.onNext(response.body) case let .failure(error): observer.onError(error) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift index 96e26a20f7d..e5802990167 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -33,15 +33,15 @@ public enum DecodableRequestBuilderError: Error { open class Response { public let statusCode: Int public let header: [String: String] - public let body: T? + public let body: T - public init(statusCode: Int, header: [String: String], body: T?) { + public init(statusCode: Int, header: [String: String], body: T) { self.statusCode = statusCode self.header = header self.body = body } - public convenience init(response: HTTPURLResponse, body: T?) { + public convenience init(response: HTTPURLResponse, body: T) { let rawHeader = response.allHeaderFields var header = [String: String]() for (key, value) in rawHeader { diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 24ab89eda79..fe7fb6683bc 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -200,60 +200,12 @@ open class URLSessionRequestBuilder: RequestBuilder { } switch T.self { - case is String.Type: - - let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - - completion(.success(Response(response: httpResponse, body: body as? T))) - - case is URL.Type: - do { - - guard error == nil else { - throw DownloadException.responseFailed - } - - guard let data = data else { - throw DownloadException.responseDataMissing - } - - let fileManager = FileManager.default - let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] - let requestURL = try getURL(from: urlRequest) - - var requestPath = try getPath(from: requestURL) - - if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { - requestPath = requestPath.appending("/\(headerFileName)") - } else { - requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") - } - - let filePath = cachesDirectory.appendingPathComponent(requestPath) - let directoryPath = filePath.deletingLastPathComponent().path - - try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) - try data.write(to: filePath, options: .atomic) - - completion(.success(Response(response: httpResponse, body: filePath as? T))) - - } catch let requestParserError as DownloadException { - completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) - } catch { - completion(.failure(ErrorResponse.error(400, data, response, error))) - } - case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) - - case is Data.Type: - - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: () as! T))) default: - - completion(.success(Response(response: httpResponse, body: data as? T))) + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") } } @@ -345,7 +297,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" - completion(.success(Response(response: httpResponse, body: body as? T))) + completion(.success(Response(response: httpResponse, body: body as! T))) case is URL.Type: do { @@ -376,7 +328,7 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) try data.write(to: filePath, options: .atomic) - completion(.success(Response(response: httpResponse, body: filePath as? T))) + completion(.success(Response(response: httpResponse, body: filePath as! T))) } catch let requestParserError as DownloadException { completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) @@ -386,11 +338,11 @@ open class URLSessionDecodableRequestBuilder: URLSessionRequestBui case is Void.Type: - completion(.success(Response(response: httpResponse, body: nil))) + completion(.success(Response(response: httpResponse, body: () as! T))) case is Data.Type: - completion(.success(Response(response: httpResponse, body: data as? T))) + completion(.success(Response(response: httpResponse, body: data as! T))) default: From e2ca42a614e6476701b87a94c05ddeb6e396c5f0 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 24 Nov 2021 15:35:54 +0800 Subject: [PATCH 15/61] Bump actions/cache from 2.1.6 to 2.1.7 (#10945) Bumps [actions/cache](https://github.com/actions/cache) from 2.1.6 to 2.1.7. - [Release notes](https://github.com/actions/cache/releases) - [Commits](https://github.com/actions/cache/compare/v2.1.6...v2.1.7) --- updated-dependencies: - dependency-name: actions/cache dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> --- .github/workflows/check-supported-versions.yaml | 4 ++-- .github/workflows/gradle-test.yaml | 4 ++-- .github/workflows/openapi-generator.yaml | 8 ++++---- .github/workflows/samples-dart.yaml | 8 ++++---- .github/workflows/samples-kotlin.yaml | 2 +- 5 files changed, 13 insertions(+), 13 deletions(-) diff --git a/.github/workflows/check-supported-versions.yaml b/.github/workflows/check-supported-versions.yaml index 3702fd30fb4..ba496f3ab5c 100644 --- a/.github/workflows/check-supported-versions.yaml +++ b/.github/workflows/check-supported-versions.yaml @@ -29,14 +29,14 @@ jobs: distribution: 'adopt' java-version: ${{ matrix.java }} - - uses: actions/cache@v2.1.6 + - uses: actions/cache@v2.1.7 with: path: ~/.m2/repository key: ${{ runner.os }}-maven-${{ hashFiles('pom.xml', 'modules/**/pom.xml') }} restore-keys: | ${{ runner.os }}-maven- - - uses: actions/cache@v2.1.6 + - uses: actions/cache@v2.1.7 with: path: | ~/.gradle/caches diff --git a/.github/workflows/gradle-test.yaml b/.github/workflows/gradle-test.yaml index 755ca996a15..6be454c68a6 100644 --- a/.github/workflows/gradle-test.yaml +++ b/.github/workflows/gradle-test.yaml @@ -40,14 +40,14 @@ jobs: java-version: 11 # Cache Gradle Dependencies - name: Setup Gradle Dependencies Cache - uses: actions/cache@v2 + uses: actions/cache@v2.1.7 with: path: ~/.gradle/caches key: ${{ runner.os }}-gradle-caches-${{ hashFiles('**/*.gradle', '**/*.gradle.kts') }} # Cache Gradle Wrapper - name: Setup Gradle Wrapper Cache - uses: actions/cache@v2 + uses: actions/cache@v2.1.7 with: path: ~/.gradle/wrapper key: ${{ runner.os }}-gradle-wrapper-${{ hashFiles('**/gradle/wrapper/gradle-wrapper.properties') }} diff --git a/.github/workflows/openapi-generator.yaml b/.github/workflows/openapi-generator.yaml index aa1a94e21e9..a5defde9826 100644 --- a/.github/workflows/openapi-generator.yaml +++ b/.github/workflows/openapi-generator.yaml @@ -21,7 +21,7 @@ jobs: with: java-version: 8 - name: Cache maven dependencies - uses: actions/cache@v2.1.6 + uses: actions/cache@v2.1.7 env: cache-name: cache-maven-repository with: @@ -56,7 +56,7 @@ jobs: with: java-version: 8 - name: Cache maven dependencies - uses: actions/cache@v2.1.6 + uses: actions/cache@v2.1.7 env: cache-name: cache-maven-repository with: @@ -162,7 +162,7 @@ jobs: with: java-version: 11 - name: Cache maven dependencies - uses: actions/cache@v2.1.6 + uses: actions/cache@v2.1.7 env: cache-name: cache-maven-repository with: @@ -194,7 +194,7 @@ jobs: with: java-version: 11 - name: Cache maven dependencies - uses: actions/cache@v2.1.6 + uses: actions/cache@v2.1.7 env: cache-name: cache-maven-repository with: diff --git a/.github/workflows/samples-dart.yaml b/.github/workflows/samples-dart.yaml index 47ae424394d..e4c94f3f125 100644 --- a/.github/workflows/samples-dart.yaml +++ b/.github/workflows/samples-dart.yaml @@ -23,7 +23,7 @@ jobs: distribution: 'adopt' java-version: 8 - name: Cache maven dependencies - uses: actions/cache@v2.1.6 + uses: actions/cache@v2.1.7 env: cache-name: maven-repository with: @@ -32,7 +32,7 @@ jobs: ~/.gradle key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} - name: Cache test dependencies - uses: actions/cache@v2.1.6 + uses: actions/cache@v2.1.7 env: cache-name: pub-cache with: @@ -56,7 +56,7 @@ jobs: distribution: 'adopt' java-version: 8 - name: Cache maven dependencies - uses: actions/cache@v2.1.6 + uses: actions/cache@v2.1.7 env: cache-name: maven-repository with: @@ -65,7 +65,7 @@ jobs: ~/.gradle key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} - name: Cache test dependencies - uses: actions/cache@v2.1.6 + uses: actions/cache@v2.1.7 env: cache-name: pub-cache with: diff --git a/.github/workflows/samples-kotlin.yaml b/.github/workflows/samples-kotlin.yaml index ddc46f801cb..39a7ea7c957 100644 --- a/.github/workflows/samples-kotlin.yaml +++ b/.github/workflows/samples-kotlin.yaml @@ -48,7 +48,7 @@ jobs: distribution: 'adopt' java-version: 8 - name: Cache maven dependencies - uses: actions/cache@v2.1.6 + uses: actions/cache@v2.1.7 env: cache-name: maven-repository with: From ca848871da40244c64f3737d247df55c144276b0 Mon Sep 17 00:00:00 2001 From: Tomasz Prus Date: Wed, 24 Nov 2021 08:54:25 +0100 Subject: [PATCH 16/61] [Python] Add missing Mock library for Python 2.7. (#10939) * [Python] Add missing Mock library for Python 2.7. * Update template for test-requirements.txt. --- .../resources/python-legacy/test-requirements.mustache | 7 ++++++- .../client/petstore/python-legacy/test-requirements.txt | 1 + .../client/petstore/python-legacy/tests/test_pet_api.py | 7 ++++++- .../client/petstore/python-legacy/test-requirements.txt | 1 + 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python-legacy/test-requirements.mustache b/modules/openapi-generator/src/main/resources/python-legacy/test-requirements.mustache index 12021b47a1c..a697e6a9e71 100644 --- a/modules/openapi-generator/src/main/resources/python-legacy/test-requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-legacy/test-requirements.mustache @@ -9,4 +9,9 @@ randomize>=0.13 pytest~=4.6.7 # needed for python 2.7+3.4 pytest-cov>=2.8.1 pytest-randomly==1.2.3 # needed for python 2.7+3.4 -{{/useNose}} \ No newline at end of file +{{/useNose}} +{{^asyncio}} +{{^tornado}} +mock; python_version<'3.0' +{{/tornado}} +{{/asyncio}} diff --git a/samples/client/petstore/python-legacy/test-requirements.txt b/samples/client/petstore/python-legacy/test-requirements.txt index 4ed3991cbec..96e37c87e98 100644 --- a/samples/client/petstore/python-legacy/test-requirements.txt +++ b/samples/client/petstore/python-legacy/test-requirements.txt @@ -1,3 +1,4 @@ pytest~=4.6.7 # needed for python 2.7+3.4 pytest-cov>=2.8.1 pytest-randomly==1.2.3 # needed for python 2.7+3.4 +mock; python_version<'3.0' diff --git a/samples/client/petstore/python-legacy/tests/test_pet_api.py b/samples/client/petstore/python-legacy/tests/test_pet_api.py index 4e894436d4b..f18bdd2dd8f 100644 --- a/samples/client/petstore/python-legacy/tests/test_pet_api.py +++ b/samples/client/petstore/python-legacy/tests/test_pet_api.py @@ -13,7 +13,12 @@ $ nosetests -v import os import unittest -from unittest.mock import patch + +try: + from unittest.mock import patch +except ImportError: + # Python 2.7 + from mock import patch import petstore_api from petstore_api import Configuration diff --git a/samples/openapi3/client/petstore/python-legacy/test-requirements.txt b/samples/openapi3/client/petstore/python-legacy/test-requirements.txt index 4ed3991cbec..96e37c87e98 100755 --- a/samples/openapi3/client/petstore/python-legacy/test-requirements.txt +++ b/samples/openapi3/client/petstore/python-legacy/test-requirements.txt @@ -1,3 +1,4 @@ pytest~=4.6.7 # needed for python 2.7+3.4 pytest-cov>=2.8.1 pytest-randomly==1.2.3 # needed for python 2.7+3.4 +mock; python_version<'3.0' From af0babf892014357368cd46d7ed29293793e4efd Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 24 Nov 2021 16:14:29 +0800 Subject: [PATCH 17/61] [C#][netcore] various improvements in HttpSigningConfiguration.cs (#10941) * various improvements in HttpSigningConfiguration.cs * update returns in xml comments --- .../HttpSigningConfiguration.mustache | 94 ++++++++-------- .../Client/HttpSigningConfiguration.cs | 102 ++++++++++-------- .../Client/HttpSigningConfiguration.cs | 102 ++++++++++-------- .../Client/HttpSigningConfiguration.cs | 102 ++++++++++-------- .../Client/HttpSigningConfiguration.cs | 102 ++++++++++-------- .../Client/HttpSigningConfiguration.cs | 102 ++++++++++-------- .../Client/HttpSigningConfiguration.cs | 102 ++++++++++-------- 7 files changed, 391 insertions(+), 315 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache index aa788ad6224..f80e584c666 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/HttpSigningConfiguration.mustache @@ -1,3 +1,5 @@ +{{>partial_header}} + using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; @@ -82,7 +84,7 @@ namespace {{packageName}}.Client /// HTTP method /// Path /// Request options - /// + /// Http signed headers internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) { const string HEADER_REQUEST_TARGET = "(request-target)"; @@ -133,7 +135,7 @@ namespace {{packageName}}.Client } else { - httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); } #else if (parameter.Value.Count > 1) @@ -178,7 +180,6 @@ namespace {{packageName}}.Client throw new Exception(string.Format("{0} not supported", HashAlgorithm)); } - foreach (var header in HttpSigningHeader) { if (header.Equals(HEADER_REQUEST_TARGET)) @@ -236,7 +237,6 @@ namespace {{packageName}}.Client foreach (var keyVal in HttpSignatureHeader) { headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); - } //Concatenate headers value separated by new line var headerValuesString = string.Join("\n", headerValuesList); @@ -252,7 +252,11 @@ namespace {{packageName}}.Client { headerSignatureStr = GetECDSASignature(signatureStringHash); } - var cryptographicScheme = "hs2019"; + else + { + throw new Exception(string.Format("Private key type {0} not supported", keyType)); + } + const string cryptographicScheme = "hs2019"; var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", KeyId, cryptographicScheme); @@ -268,9 +272,7 @@ namespace {{packageName}}.Client authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", headersKeysString, headerSignatureStr); - HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); - return HttpSignedRequestHeader; } @@ -302,14 +304,17 @@ namespace {{packageName}}.Client var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); return Convert.ToBase64String(signedbytes); } - return string.Empty; + else + { + return string.Empty; + } } /// /// Gets the ECDSA signature /// /// - /// + /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { if (!File.Exists(KeyFilePath)) @@ -317,8 +322,8 @@ namespace {{packageName}}.Client throw new Exception("key file path does not exist."); } - var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; - var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); @@ -355,10 +360,9 @@ namespace {{packageName}}.Client #else throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); #endif - } - private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) { var derBytes = new List(); byte derLength = 68; //default length for ECDSA code signing bit 0x44 @@ -481,7 +485,7 @@ namespace {{packageName}}.Client byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); - if (!(str.ReadLine() == "")) + if (str.ReadLine() != "") { return null; } @@ -512,7 +516,7 @@ namespace {{packageName}}.Client private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); @@ -549,40 +553,40 @@ namespace {{packageName}}.Client //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); + bytesModulus = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); + bytesE = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); + bytesD = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); + bytesP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); + bytesQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); + bytesDP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); + bytesDQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); + bytesIQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); - RSAparams.Modulus = MODULUS; - RSAparams.Exponent = E; - RSAparams.D = D; - RSAparams.P = P; - RSAparams.Q = Q; - RSAparams.DP = DP; - RSAparams.DQ = DQ; - RSAparams.InverseQ = IQ; + RSAparams.Modulus = bytesModulus; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDP; + RSAparams.DQ = bytesDQ; + RSAparams.InverseQ = bytesIQ; RSA.ImportParameters(RSAparams); return RSA; } @@ -637,7 +641,7 @@ namespace {{packageName}}.Client private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) { IntPtr unmanagedPswd = IntPtr.Zero; - int HASHLENGTH = 16; //MD5 bytes + const int HASHLENGTH = 16; //MD5 bytes byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results byte[] psbytes = new byte[secpswd.Length]; @@ -670,7 +674,9 @@ namespace {{packageName}}.Client } for (int i = 0; i < count; i++) + { result = md5.ComputeHash(result); + } Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial } byte[] deskey = new byte[24]; @@ -708,7 +714,7 @@ namespace {{packageName}}.Client /// Detect the key type from the pem file. /// /// key file path in pem format - /// + /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { if (!File.Exists(keyFilePath)) @@ -716,39 +722,37 @@ namespace {{packageName}}.Client throw new Exception("Key file path does not exist."); } - var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; - var ecPrivateKeyFooter = "END EC PRIVATE KEY"; - var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; - var rsaPrivateFooter = "END RSA PRIVATE KEY"; + const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + const string ecPrivateKeyFooter = "END EC PRIVATE KEY"; + const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + const string rsaPrivateFooter = "END RSA PRIVATE KEY"; //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; - var keyType = PrivateKeyType.None; + PrivateKeyType keyType; var key = File.ReadAllLines(keyFilePath); - if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) { keyType = PrivateKeyType.RSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { keyType = PrivateKeyType.ECDSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { - /* this type of key can hold many type different types of private key, but here due lack of pem header - Considering this as EC key - */ + // this type of key can hold many type different types of private key, but here due lack of pem header + // Considering this as EC key //TODO :- update the key based on oid keyType = PrivateKeyType.ECDSA; } else { throw new Exception("Either the key is invalid or key is not supported"); - } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 9293bc51d32..f3eaf3c5ade 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -1,3 +1,13 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; @@ -82,7 +92,7 @@ namespace Org.OpenAPITools.Client /// HTTP method /// Path /// Request options - /// + /// Http signed headers internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) { const string HEADER_REQUEST_TARGET = "(request-target)"; @@ -133,7 +143,7 @@ namespace Org.OpenAPITools.Client } else { - httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); } #else if (parameter.Value.Count > 1) @@ -178,7 +188,6 @@ namespace Org.OpenAPITools.Client throw new Exception(string.Format("{0} not supported", HashAlgorithm)); } - foreach (var header in HttpSigningHeader) { if (header.Equals(HEADER_REQUEST_TARGET)) @@ -236,7 +245,6 @@ namespace Org.OpenAPITools.Client foreach (var keyVal in HttpSignatureHeader) { headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); - } //Concatenate headers value separated by new line var headerValuesString = string.Join("\n", headerValuesList); @@ -252,7 +260,11 @@ namespace Org.OpenAPITools.Client { headerSignatureStr = GetECDSASignature(signatureStringHash); } - var cryptographicScheme = "hs2019"; + else + { + throw new Exception(string.Format("Private key type {0} not supported", keyType)); + } + const string cryptographicScheme = "hs2019"; var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", KeyId, cryptographicScheme); @@ -268,9 +280,7 @@ namespace Org.OpenAPITools.Client authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", headersKeysString, headerSignatureStr); - HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); - return HttpSignedRequestHeader; } @@ -302,14 +312,17 @@ namespace Org.OpenAPITools.Client var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); return Convert.ToBase64String(signedbytes); } - return string.Empty; + else + { + return string.Empty; + } } /// /// Gets the ECDSA signature /// /// - /// + /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { if (!File.Exists(KeyFilePath)) @@ -317,8 +330,8 @@ namespace Org.OpenAPITools.Client throw new Exception("key file path does not exist."); } - var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; - var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); @@ -355,10 +368,9 @@ namespace Org.OpenAPITools.Client #else throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); #endif - } - private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) { var derBytes = new List(); byte derLength = 68; //default length for ECDSA code signing bit 0x44 @@ -481,7 +493,7 @@ namespace Org.OpenAPITools.Client byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); - if (!(str.ReadLine() == "")) + if (str.ReadLine() != "") { return null; } @@ -512,7 +524,7 @@ namespace Org.OpenAPITools.Client private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); @@ -549,40 +561,40 @@ namespace Org.OpenAPITools.Client //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); + bytesModulus = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); + bytesE = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); + bytesD = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); + bytesP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); + bytesQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); + bytesDP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); + bytesDQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); + bytesIQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); - RSAparams.Modulus = MODULUS; - RSAparams.Exponent = E; - RSAparams.D = D; - RSAparams.P = P; - RSAparams.Q = Q; - RSAparams.DP = DP; - RSAparams.DQ = DQ; - RSAparams.InverseQ = IQ; + RSAparams.Modulus = bytesModulus; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDP; + RSAparams.DQ = bytesDQ; + RSAparams.InverseQ = bytesIQ; RSA.ImportParameters(RSAparams); return RSA; } @@ -637,7 +649,7 @@ namespace Org.OpenAPITools.Client private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) { IntPtr unmanagedPswd = IntPtr.Zero; - int HASHLENGTH = 16; //MD5 bytes + const int HASHLENGTH = 16; //MD5 bytes byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results byte[] psbytes = new byte[secpswd.Length]; @@ -670,7 +682,9 @@ namespace Org.OpenAPITools.Client } for (int i = 0; i < count; i++) + { result = md5.ComputeHash(result); + } Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial } byte[] deskey = new byte[24]; @@ -708,7 +722,7 @@ namespace Org.OpenAPITools.Client /// Detect the key type from the pem file. /// /// key file path in pem format - /// + /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { if (!File.Exists(keyFilePath)) @@ -716,39 +730,37 @@ namespace Org.OpenAPITools.Client throw new Exception("Key file path does not exist."); } - var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; - var ecPrivateKeyFooter = "END EC PRIVATE KEY"; - var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; - var rsaPrivateFooter = "END RSA PRIVATE KEY"; + const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + const string ecPrivateKeyFooter = "END EC PRIVATE KEY"; + const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + const string rsaPrivateFooter = "END RSA PRIVATE KEY"; //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; - var keyType = PrivateKeyType.None; + PrivateKeyType keyType; var key = File.ReadAllLines(keyFilePath); - if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) { keyType = PrivateKeyType.RSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { keyType = PrivateKeyType.ECDSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { - /* this type of key can hold many type different types of private key, but here due lack of pem header - Considering this as EC key - */ + // this type of key can hold many type different types of private key, but here due lack of pem header + // Considering this as EC key //TODO :- update the key based on oid keyType = PrivateKeyType.ECDSA; } else { throw new Exception("Either the key is invalid or key is not supported"); - } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 9293bc51d32..f3eaf3c5ade 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -1,3 +1,13 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; @@ -82,7 +92,7 @@ namespace Org.OpenAPITools.Client /// HTTP method /// Path /// Request options - /// + /// Http signed headers internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) { const string HEADER_REQUEST_TARGET = "(request-target)"; @@ -133,7 +143,7 @@ namespace Org.OpenAPITools.Client } else { - httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); } #else if (parameter.Value.Count > 1) @@ -178,7 +188,6 @@ namespace Org.OpenAPITools.Client throw new Exception(string.Format("{0} not supported", HashAlgorithm)); } - foreach (var header in HttpSigningHeader) { if (header.Equals(HEADER_REQUEST_TARGET)) @@ -236,7 +245,6 @@ namespace Org.OpenAPITools.Client foreach (var keyVal in HttpSignatureHeader) { headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); - } //Concatenate headers value separated by new line var headerValuesString = string.Join("\n", headerValuesList); @@ -252,7 +260,11 @@ namespace Org.OpenAPITools.Client { headerSignatureStr = GetECDSASignature(signatureStringHash); } - var cryptographicScheme = "hs2019"; + else + { + throw new Exception(string.Format("Private key type {0} not supported", keyType)); + } + const string cryptographicScheme = "hs2019"; var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", KeyId, cryptographicScheme); @@ -268,9 +280,7 @@ namespace Org.OpenAPITools.Client authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", headersKeysString, headerSignatureStr); - HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); - return HttpSignedRequestHeader; } @@ -302,14 +312,17 @@ namespace Org.OpenAPITools.Client var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); return Convert.ToBase64String(signedbytes); } - return string.Empty; + else + { + return string.Empty; + } } /// /// Gets the ECDSA signature /// /// - /// + /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { if (!File.Exists(KeyFilePath)) @@ -317,8 +330,8 @@ namespace Org.OpenAPITools.Client throw new Exception("key file path does not exist."); } - var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; - var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); @@ -355,10 +368,9 @@ namespace Org.OpenAPITools.Client #else throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); #endif - } - private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) { var derBytes = new List(); byte derLength = 68; //default length for ECDSA code signing bit 0x44 @@ -481,7 +493,7 @@ namespace Org.OpenAPITools.Client byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); - if (!(str.ReadLine() == "")) + if (str.ReadLine() != "") { return null; } @@ -512,7 +524,7 @@ namespace Org.OpenAPITools.Client private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); @@ -549,40 +561,40 @@ namespace Org.OpenAPITools.Client //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); + bytesModulus = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); + bytesE = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); + bytesD = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); + bytesP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); + bytesQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); + bytesDP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); + bytesDQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); + bytesIQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); - RSAparams.Modulus = MODULUS; - RSAparams.Exponent = E; - RSAparams.D = D; - RSAparams.P = P; - RSAparams.Q = Q; - RSAparams.DP = DP; - RSAparams.DQ = DQ; - RSAparams.InverseQ = IQ; + RSAparams.Modulus = bytesModulus; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDP; + RSAparams.DQ = bytesDQ; + RSAparams.InverseQ = bytesIQ; RSA.ImportParameters(RSAparams); return RSA; } @@ -637,7 +649,7 @@ namespace Org.OpenAPITools.Client private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) { IntPtr unmanagedPswd = IntPtr.Zero; - int HASHLENGTH = 16; //MD5 bytes + const int HASHLENGTH = 16; //MD5 bytes byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results byte[] psbytes = new byte[secpswd.Length]; @@ -670,7 +682,9 @@ namespace Org.OpenAPITools.Client } for (int i = 0; i < count; i++) + { result = md5.ComputeHash(result); + } Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial } byte[] deskey = new byte[24]; @@ -708,7 +722,7 @@ namespace Org.OpenAPITools.Client /// Detect the key type from the pem file. /// /// key file path in pem format - /// + /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { if (!File.Exists(keyFilePath)) @@ -716,39 +730,37 @@ namespace Org.OpenAPITools.Client throw new Exception("Key file path does not exist."); } - var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; - var ecPrivateKeyFooter = "END EC PRIVATE KEY"; - var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; - var rsaPrivateFooter = "END RSA PRIVATE KEY"; + const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + const string ecPrivateKeyFooter = "END EC PRIVATE KEY"; + const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + const string rsaPrivateFooter = "END RSA PRIVATE KEY"; //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; - var keyType = PrivateKeyType.None; + PrivateKeyType keyType; var key = File.ReadAllLines(keyFilePath); - if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) { keyType = PrivateKeyType.RSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { keyType = PrivateKeyType.ECDSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { - /* this type of key can hold many type different types of private key, but here due lack of pem header - Considering this as EC key - */ + // this type of key can hold many type different types of private key, but here due lack of pem header + // Considering this as EC key //TODO :- update the key based on oid keyType = PrivateKeyType.ECDSA; } else { throw new Exception("Either the key is invalid or key is not supported"); - } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 9293bc51d32..f3eaf3c5ade 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -1,3 +1,13 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; @@ -82,7 +92,7 @@ namespace Org.OpenAPITools.Client /// HTTP method /// Path /// Request options - /// + /// Http signed headers internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) { const string HEADER_REQUEST_TARGET = "(request-target)"; @@ -133,7 +143,7 @@ namespace Org.OpenAPITools.Client } else { - httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); } #else if (parameter.Value.Count > 1) @@ -178,7 +188,6 @@ namespace Org.OpenAPITools.Client throw new Exception(string.Format("{0} not supported", HashAlgorithm)); } - foreach (var header in HttpSigningHeader) { if (header.Equals(HEADER_REQUEST_TARGET)) @@ -236,7 +245,6 @@ namespace Org.OpenAPITools.Client foreach (var keyVal in HttpSignatureHeader) { headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); - } //Concatenate headers value separated by new line var headerValuesString = string.Join("\n", headerValuesList); @@ -252,7 +260,11 @@ namespace Org.OpenAPITools.Client { headerSignatureStr = GetECDSASignature(signatureStringHash); } - var cryptographicScheme = "hs2019"; + else + { + throw new Exception(string.Format("Private key type {0} not supported", keyType)); + } + const string cryptographicScheme = "hs2019"; var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", KeyId, cryptographicScheme); @@ -268,9 +280,7 @@ namespace Org.OpenAPITools.Client authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", headersKeysString, headerSignatureStr); - HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); - return HttpSignedRequestHeader; } @@ -302,14 +312,17 @@ namespace Org.OpenAPITools.Client var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); return Convert.ToBase64String(signedbytes); } - return string.Empty; + else + { + return string.Empty; + } } /// /// Gets the ECDSA signature /// /// - /// + /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { if (!File.Exists(KeyFilePath)) @@ -317,8 +330,8 @@ namespace Org.OpenAPITools.Client throw new Exception("key file path does not exist."); } - var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; - var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); @@ -355,10 +368,9 @@ namespace Org.OpenAPITools.Client #else throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); #endif - } - private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) { var derBytes = new List(); byte derLength = 68; //default length for ECDSA code signing bit 0x44 @@ -481,7 +493,7 @@ namespace Org.OpenAPITools.Client byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); - if (!(str.ReadLine() == "")) + if (str.ReadLine() != "") { return null; } @@ -512,7 +524,7 @@ namespace Org.OpenAPITools.Client private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); @@ -549,40 +561,40 @@ namespace Org.OpenAPITools.Client //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); + bytesModulus = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); + bytesE = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); + bytesD = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); + bytesP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); + bytesQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); + bytesDP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); + bytesDQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); + bytesIQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); - RSAparams.Modulus = MODULUS; - RSAparams.Exponent = E; - RSAparams.D = D; - RSAparams.P = P; - RSAparams.Q = Q; - RSAparams.DP = DP; - RSAparams.DQ = DQ; - RSAparams.InverseQ = IQ; + RSAparams.Modulus = bytesModulus; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDP; + RSAparams.DQ = bytesDQ; + RSAparams.InverseQ = bytesIQ; RSA.ImportParameters(RSAparams); return RSA; } @@ -637,7 +649,7 @@ namespace Org.OpenAPITools.Client private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) { IntPtr unmanagedPswd = IntPtr.Zero; - int HASHLENGTH = 16; //MD5 bytes + const int HASHLENGTH = 16; //MD5 bytes byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results byte[] psbytes = new byte[secpswd.Length]; @@ -670,7 +682,9 @@ namespace Org.OpenAPITools.Client } for (int i = 0; i < count; i++) + { result = md5.ComputeHash(result); + } Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial } byte[] deskey = new byte[24]; @@ -708,7 +722,7 @@ namespace Org.OpenAPITools.Client /// Detect the key type from the pem file. /// /// key file path in pem format - /// + /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { if (!File.Exists(keyFilePath)) @@ -716,39 +730,37 @@ namespace Org.OpenAPITools.Client throw new Exception("Key file path does not exist."); } - var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; - var ecPrivateKeyFooter = "END EC PRIVATE KEY"; - var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; - var rsaPrivateFooter = "END RSA PRIVATE KEY"; + const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + const string ecPrivateKeyFooter = "END EC PRIVATE KEY"; + const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + const string rsaPrivateFooter = "END RSA PRIVATE KEY"; //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; - var keyType = PrivateKeyType.None; + PrivateKeyType keyType; var key = File.ReadAllLines(keyFilePath); - if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) { keyType = PrivateKeyType.RSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { keyType = PrivateKeyType.ECDSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { - /* this type of key can hold many type different types of private key, but here due lack of pem header - Considering this as EC key - */ + // this type of key can hold many type different types of private key, but here due lack of pem header + // Considering this as EC key //TODO :- update the key based on oid keyType = PrivateKeyType.ECDSA; } else { throw new Exception("Either the key is invalid or key is not supported"); - } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 9293bc51d32..f3eaf3c5ade 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -1,3 +1,13 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; @@ -82,7 +92,7 @@ namespace Org.OpenAPITools.Client /// HTTP method /// Path /// Request options - /// + /// Http signed headers internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) { const string HEADER_REQUEST_TARGET = "(request-target)"; @@ -133,7 +143,7 @@ namespace Org.OpenAPITools.Client } else { - httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); } #else if (parameter.Value.Count > 1) @@ -178,7 +188,6 @@ namespace Org.OpenAPITools.Client throw new Exception(string.Format("{0} not supported", HashAlgorithm)); } - foreach (var header in HttpSigningHeader) { if (header.Equals(HEADER_REQUEST_TARGET)) @@ -236,7 +245,6 @@ namespace Org.OpenAPITools.Client foreach (var keyVal in HttpSignatureHeader) { headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); - } //Concatenate headers value separated by new line var headerValuesString = string.Join("\n", headerValuesList); @@ -252,7 +260,11 @@ namespace Org.OpenAPITools.Client { headerSignatureStr = GetECDSASignature(signatureStringHash); } - var cryptographicScheme = "hs2019"; + else + { + throw new Exception(string.Format("Private key type {0} not supported", keyType)); + } + const string cryptographicScheme = "hs2019"; var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", KeyId, cryptographicScheme); @@ -268,9 +280,7 @@ namespace Org.OpenAPITools.Client authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", headersKeysString, headerSignatureStr); - HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); - return HttpSignedRequestHeader; } @@ -302,14 +312,17 @@ namespace Org.OpenAPITools.Client var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); return Convert.ToBase64String(signedbytes); } - return string.Empty; + else + { + return string.Empty; + } } /// /// Gets the ECDSA signature /// /// - /// + /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { if (!File.Exists(KeyFilePath)) @@ -317,8 +330,8 @@ namespace Org.OpenAPITools.Client throw new Exception("key file path does not exist."); } - var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; - var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); @@ -355,10 +368,9 @@ namespace Org.OpenAPITools.Client #else throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); #endif - } - private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) { var derBytes = new List(); byte derLength = 68; //default length for ECDSA code signing bit 0x44 @@ -481,7 +493,7 @@ namespace Org.OpenAPITools.Client byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); - if (!(str.ReadLine() == "")) + if (str.ReadLine() != "") { return null; } @@ -512,7 +524,7 @@ namespace Org.OpenAPITools.Client private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); @@ -549,40 +561,40 @@ namespace Org.OpenAPITools.Client //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); + bytesModulus = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); + bytesE = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); + bytesD = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); + bytesP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); + bytesQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); + bytesDP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); + bytesDQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); + bytesIQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); - RSAparams.Modulus = MODULUS; - RSAparams.Exponent = E; - RSAparams.D = D; - RSAparams.P = P; - RSAparams.Q = Q; - RSAparams.DP = DP; - RSAparams.DQ = DQ; - RSAparams.InverseQ = IQ; + RSAparams.Modulus = bytesModulus; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDP; + RSAparams.DQ = bytesDQ; + RSAparams.InverseQ = bytesIQ; RSA.ImportParameters(RSAparams); return RSA; } @@ -637,7 +649,7 @@ namespace Org.OpenAPITools.Client private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) { IntPtr unmanagedPswd = IntPtr.Zero; - int HASHLENGTH = 16; //MD5 bytes + const int HASHLENGTH = 16; //MD5 bytes byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results byte[] psbytes = new byte[secpswd.Length]; @@ -670,7 +682,9 @@ namespace Org.OpenAPITools.Client } for (int i = 0; i < count; i++) + { result = md5.ComputeHash(result); + } Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial } byte[] deskey = new byte[24]; @@ -708,7 +722,7 @@ namespace Org.OpenAPITools.Client /// Detect the key type from the pem file. /// /// key file path in pem format - /// + /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { if (!File.Exists(keyFilePath)) @@ -716,39 +730,37 @@ namespace Org.OpenAPITools.Client throw new Exception("Key file path does not exist."); } - var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; - var ecPrivateKeyFooter = "END EC PRIVATE KEY"; - var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; - var rsaPrivateFooter = "END RSA PRIVATE KEY"; + const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + const string ecPrivateKeyFooter = "END EC PRIVATE KEY"; + const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + const string rsaPrivateFooter = "END RSA PRIVATE KEY"; //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; - var keyType = PrivateKeyType.None; + PrivateKeyType keyType; var key = File.ReadAllLines(keyFilePath); - if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) { keyType = PrivateKeyType.RSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { keyType = PrivateKeyType.ECDSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { - /* this type of key can hold many type different types of private key, but here due lack of pem header - Considering this as EC key - */ + // this type of key can hold many type different types of private key, but here due lack of pem header + // Considering this as EC key //TODO :- update the key based on oid keyType = PrivateKeyType.ECDSA; } else { throw new Exception("Either the key is invalid or key is not supported"); - } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 9293bc51d32..f3eaf3c5ade 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -1,3 +1,13 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; @@ -82,7 +92,7 @@ namespace Org.OpenAPITools.Client /// HTTP method /// Path /// Request options - /// + /// Http signed headers internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) { const string HEADER_REQUEST_TARGET = "(request-target)"; @@ -133,7 +143,7 @@ namespace Org.OpenAPITools.Client } else { - httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); } #else if (parameter.Value.Count > 1) @@ -178,7 +188,6 @@ namespace Org.OpenAPITools.Client throw new Exception(string.Format("{0} not supported", HashAlgorithm)); } - foreach (var header in HttpSigningHeader) { if (header.Equals(HEADER_REQUEST_TARGET)) @@ -236,7 +245,6 @@ namespace Org.OpenAPITools.Client foreach (var keyVal in HttpSignatureHeader) { headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); - } //Concatenate headers value separated by new line var headerValuesString = string.Join("\n", headerValuesList); @@ -252,7 +260,11 @@ namespace Org.OpenAPITools.Client { headerSignatureStr = GetECDSASignature(signatureStringHash); } - var cryptographicScheme = "hs2019"; + else + { + throw new Exception(string.Format("Private key type {0} not supported", keyType)); + } + const string cryptographicScheme = "hs2019"; var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", KeyId, cryptographicScheme); @@ -268,9 +280,7 @@ namespace Org.OpenAPITools.Client authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", headersKeysString, headerSignatureStr); - HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); - return HttpSignedRequestHeader; } @@ -302,14 +312,17 @@ namespace Org.OpenAPITools.Client var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); return Convert.ToBase64String(signedbytes); } - return string.Empty; + else + { + return string.Empty; + } } /// /// Gets the ECDSA signature /// /// - /// + /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { if (!File.Exists(KeyFilePath)) @@ -317,8 +330,8 @@ namespace Org.OpenAPITools.Client throw new Exception("key file path does not exist."); } - var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; - var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); @@ -355,10 +368,9 @@ namespace Org.OpenAPITools.Client #else throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); #endif - } - private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) { var derBytes = new List(); byte derLength = 68; //default length for ECDSA code signing bit 0x44 @@ -481,7 +493,7 @@ namespace Org.OpenAPITools.Client byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); - if (!(str.ReadLine() == "")) + if (str.ReadLine() != "") { return null; } @@ -512,7 +524,7 @@ namespace Org.OpenAPITools.Client private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); @@ -549,40 +561,40 @@ namespace Org.OpenAPITools.Client //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); + bytesModulus = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); + bytesE = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); + bytesD = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); + bytesP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); + bytesQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); + bytesDP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); + bytesDQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); + bytesIQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); - RSAparams.Modulus = MODULUS; - RSAparams.Exponent = E; - RSAparams.D = D; - RSAparams.P = P; - RSAparams.Q = Q; - RSAparams.DP = DP; - RSAparams.DQ = DQ; - RSAparams.InverseQ = IQ; + RSAparams.Modulus = bytesModulus; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDP; + RSAparams.DQ = bytesDQ; + RSAparams.InverseQ = bytesIQ; RSA.ImportParameters(RSAparams); return RSA; } @@ -637,7 +649,7 @@ namespace Org.OpenAPITools.Client private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) { IntPtr unmanagedPswd = IntPtr.Zero; - int HASHLENGTH = 16; //MD5 bytes + const int HASHLENGTH = 16; //MD5 bytes byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results byte[] psbytes = new byte[secpswd.Length]; @@ -670,7 +682,9 @@ namespace Org.OpenAPITools.Client } for (int i = 0; i < count; i++) + { result = md5.ComputeHash(result); + } Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial } byte[] deskey = new byte[24]; @@ -708,7 +722,7 @@ namespace Org.OpenAPITools.Client /// Detect the key type from the pem file. /// /// key file path in pem format - /// + /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { if (!File.Exists(keyFilePath)) @@ -716,39 +730,37 @@ namespace Org.OpenAPITools.Client throw new Exception("Key file path does not exist."); } - var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; - var ecPrivateKeyFooter = "END EC PRIVATE KEY"; - var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; - var rsaPrivateFooter = "END RSA PRIVATE KEY"; + const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + const string ecPrivateKeyFooter = "END EC PRIVATE KEY"; + const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + const string rsaPrivateFooter = "END RSA PRIVATE KEY"; //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; - var keyType = PrivateKeyType.None; + PrivateKeyType keyType; var key = File.ReadAllLines(keyFilePath); - if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) { keyType = PrivateKeyType.RSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { keyType = PrivateKeyType.ECDSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { - /* this type of key can hold many type different types of private key, but here due lack of pem header - Considering this as EC key - */ + // this type of key can hold many type different types of private key, but here due lack of pem header + // Considering this as EC key //TODO :- update the key based on oid keyType = PrivateKeyType.ECDSA; } else { throw new Exception("Either the key is invalid or key is not supported"); - } return keyType; } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 9293bc51d32..f3eaf3c5ade 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -1,3 +1,13 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; @@ -82,7 +92,7 @@ namespace Org.OpenAPITools.Client /// HTTP method /// Path /// Request options - /// + /// Http signed headers internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) { const string HEADER_REQUEST_TARGET = "(request-target)"; @@ -133,7 +143,7 @@ namespace Org.OpenAPITools.Client } else { - httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); } #else if (parameter.Value.Count > 1) @@ -178,7 +188,6 @@ namespace Org.OpenAPITools.Client throw new Exception(string.Format("{0} not supported", HashAlgorithm)); } - foreach (var header in HttpSigningHeader) { if (header.Equals(HEADER_REQUEST_TARGET)) @@ -236,7 +245,6 @@ namespace Org.OpenAPITools.Client foreach (var keyVal in HttpSignatureHeader) { headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); - } //Concatenate headers value separated by new line var headerValuesString = string.Join("\n", headerValuesList); @@ -252,7 +260,11 @@ namespace Org.OpenAPITools.Client { headerSignatureStr = GetECDSASignature(signatureStringHash); } - var cryptographicScheme = "hs2019"; + else + { + throw new Exception(string.Format("Private key type {0} not supported", keyType)); + } + const string cryptographicScheme = "hs2019"; var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", KeyId, cryptographicScheme); @@ -268,9 +280,7 @@ namespace Org.OpenAPITools.Client authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", headersKeysString, headerSignatureStr); - HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); - return HttpSignedRequestHeader; } @@ -302,14 +312,17 @@ namespace Org.OpenAPITools.Client var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); return Convert.ToBase64String(signedbytes); } - return string.Empty; + else + { + return string.Empty; + } } /// /// Gets the ECDSA signature /// /// - /// + /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { if (!File.Exists(KeyFilePath)) @@ -317,8 +330,8 @@ namespace Org.OpenAPITools.Client throw new Exception("key file path does not exist."); } - var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; - var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + const string ecKeyFooter = "-----END EC PRIVATE KEY-----"; var keyStr = File.ReadAllText(KeyFilePath); var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); @@ -355,10 +368,9 @@ namespace Org.OpenAPITools.Client #else throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); #endif - } - private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) { var derBytes = new List(); byte derLength = 68; //default length for ECDSA code signing bit 0x44 @@ -481,7 +493,7 @@ namespace Org.OpenAPITools.Client byte[] salt = new byte[saltstr.Length / 2]; for (int i = 0; i < salt.Length; i++) salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); - if (!(str.ReadLine() == "")) + if (str.ReadLine() != "") { return null; } @@ -512,7 +524,7 @@ namespace Org.OpenAPITools.Client private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) { - byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + byte[] bytesModulus, bytesE, bytesD, bytesP, bytesQ, bytesDP, bytesDQ, bytesIQ; // --------- Set up stream to decode the asn.1 encoded RSA private key ------ MemoryStream mem = new MemoryStream(privkey); @@ -549,40 +561,40 @@ namespace Org.OpenAPITools.Client //------ all private key components are Integer sequences ---- elems = GetIntegerSize(binr); - MODULUS = binr.ReadBytes(elems); + bytesModulus = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - E = binr.ReadBytes(elems); + bytesE = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - D = binr.ReadBytes(elems); + bytesD = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - P = binr.ReadBytes(elems); + bytesP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - Q = binr.ReadBytes(elems); + bytesQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DP = binr.ReadBytes(elems); + bytesDP = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - DQ = binr.ReadBytes(elems); + bytesDQ = binr.ReadBytes(elems); elems = GetIntegerSize(binr); - IQ = binr.ReadBytes(elems); + bytesIQ = binr.ReadBytes(elems); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); RSAParameters RSAparams = new RSAParameters(); - RSAparams.Modulus = MODULUS; - RSAparams.Exponent = E; - RSAparams.D = D; - RSAparams.P = P; - RSAparams.Q = Q; - RSAparams.DP = DP; - RSAparams.DQ = DQ; - RSAparams.InverseQ = IQ; + RSAparams.Modulus = bytesModulus; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDP; + RSAparams.DQ = bytesDQ; + RSAparams.InverseQ = bytesIQ; RSA.ImportParameters(RSAparams); return RSA; } @@ -637,7 +649,7 @@ namespace Org.OpenAPITools.Client private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) { IntPtr unmanagedPswd = IntPtr.Zero; - int HASHLENGTH = 16; //MD5 bytes + const int HASHLENGTH = 16; //MD5 bytes byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results byte[] psbytes = new byte[secpswd.Length]; @@ -670,7 +682,9 @@ namespace Org.OpenAPITools.Client } for (int i = 0; i < count; i++) + { result = md5.ComputeHash(result); + } Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial } byte[] deskey = new byte[24]; @@ -708,7 +722,7 @@ namespace Org.OpenAPITools.Client /// Detect the key type from the pem file. /// /// key file path in pem format - /// + /// Private Key Type private PrivateKeyType GetKeyType(string keyFilePath) { if (!File.Exists(keyFilePath)) @@ -716,39 +730,37 @@ namespace Org.OpenAPITools.Client throw new Exception("Key file path does not exist."); } - var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; - var ecPrivateKeyFooter = "END EC PRIVATE KEY"; - var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; - var rsaPrivateFooter = "END RSA PRIVATE KEY"; + const string ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + const string ecPrivateKeyFooter = "END EC PRIVATE KEY"; + const string rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + const string rsaPrivateFooter = "END RSA PRIVATE KEY"; //var pkcs8Header = "BEGIN PRIVATE KEY"; //var pkcs8Footer = "END PRIVATE KEY"; - var keyType = PrivateKeyType.None; + PrivateKeyType keyType; var key = File.ReadAllLines(keyFilePath); - if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + if (key[0].Contains(rsaPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) { keyType = PrivateKeyType.RSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { keyType = PrivateKeyType.ECDSA; } - else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + else if (key[0].Contains(ecPrivateKeyHeader) && key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) { - /* this type of key can hold many type different types of private key, but here due lack of pem header - Considering this as EC key - */ + // this type of key can hold many type different types of private key, but here due lack of pem header + // Considering this as EC key //TODO :- update the key based on oid keyType = PrivateKeyType.ECDSA; } else { throw new Exception("Either the key is invalid or key is not supported"); - } return keyType; } From d01ad0524c4cf8f602f6305826ded1173e83d387 Mon Sep 17 00:00:00 2001 From: Sheldon Young Date: Wed, 24 Nov 2021 01:20:44 -0800 Subject: [PATCH 18/61] [rust] Update to modern hyper and futures crates (#9919) * [rust] Update to modern hyper and futures crates * [rust] Update to modern hyper and futures crates --- .../src/main/resources/rust/Cargo.mustache | 6 +- .../main/resources/rust/hyper/api.mustache | 25 +- .../resources/rust/hyper/api_mod.mustache | 48 ++-- .../main/resources/rust/hyper/client.mustache | 3 +- .../rust/hyper/configuration.mustache | 8 +- .../src/main/resources/rust/request.rs | 225 +++++++++--------- .../petstore/rust/hyper/petstore/Cargo.toml | 6 +- .../rust/hyper/petstore/src/apis/client.rs | 3 +- .../hyper/petstore/src/apis/configuration.rs | 8 +- .../rust/hyper/petstore/src/apis/mod.rs | 48 ++-- .../rust/hyper/petstore/src/apis/pet_api.rs | 69 +++--- .../rust/hyper/petstore/src/apis/request.rs | 225 +++++++++--------- .../rust/hyper/petstore/src/apis/store_api.rs | 41 ++-- .../rust/hyper/petstore/src/apis/user_api.rs | 99 ++++---- 14 files changed, 409 insertions(+), 405 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/rust/Cargo.mustache b/modules/openapi-generator/src/main/resources/rust/Cargo.mustache index 53c02a6f286..f8da736d432 100644 --- a/modules/openapi-generator/src/main/resources/rust/Cargo.mustache +++ b/modules/openapi-generator/src/main/resources/rust/Cargo.mustache @@ -10,10 +10,12 @@ serde_derive = "^1.0" serde_json = "^1.0" url = "^2.2" {{#hyper}} -hyper = "~0.11" +hyper = { version = "~0.14", features = ["full"] } +hyper-tls = "~0.5" +http = "~0.2" serde_yaml = "0.7" base64 = "~0.7.0" -futures = "0.1.23" +futures = "^0.3" {{/hyper}} {{#reqwest}} {{^supportAsync}} diff --git a/modules/openapi-generator/src/main/resources/rust/hyper/api.mustache b/modules/openapi-generator/src/main/resources/rust/hyper/api.mustache index e2833f16ed9..a055014fb5c 100644 --- a/modules/openapi-generator/src/main/resources/rust/hyper/api.mustache +++ b/modules/openapi-generator/src/main/resources/rust/hyper/api.mustache @@ -1,21 +1,23 @@ {{>partial_header}} use std::rc::Rc; use std::borrow::Borrow; +use std::pin::Pin; #[allow(unused_imports)] use std::option::Option; use hyper; -use serde_json; use futures::Future; use super::{Error, configuration}; use super::request as __internal_request; -pub struct {{{classname}}}Client { +pub struct {{{classname}}}Client + where C: Clone + std::marker::Send + Sync + 'static { configuration: Rc>, } -impl {{{classname}}}Client { +impl {{{classname}}}Client + where C: Clone + std::marker::Send + Sync { pub fn new(configuration: Rc>) -> {{{classname}}}Client { {{{classname}}}Client { configuration, @@ -26,16 +28,18 @@ impl {{{classname}}}Client { pub trait {{{classname}}} { {{#operations}} {{#operation}} - fn {{{operationId}}}(&self, {{#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}}{{^-last}}, {{/-last}}{{/allParams}}) -> Box>>; + fn {{{operationId}}}(&self, {{#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}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin>>>; {{/operation}} {{/operations}} } -impl{{{classname}}} for {{{classname}}}Client { -{{#operations}} -{{#operation}} - fn {{{operationId}}}(&self, {{#allParams}}{{{paramName}}}: {{^required}}Option<{{/required}}{{#required}}{{#isNullable}}Option<{{/isNullable}}{{/required}}{{#isString}}{{^isUuid}}&str{{/isUuid}}{{/isString}}{{#isUuid}}&str{{/isUuid}}{{^isString}}{{^isUuid}}{{^isPrimitiveType}}{{^isContainer}}crate::models::{{/isContainer}}{{/isPrimitiveType}}{{{dataType}}}{{/isUuid}}{{/isString}}{{^required}}>{{/required}}{{#required}}{{#isNullable}}>{{/isNullable}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::{{{httpMethod}}}, "{{{path}}}".to_string()) +impl{{{classname}}} for {{{classname}}}Client + where C: Clone + std::marker::Send + Sync { + {{#operations}} + {{#operation}} + #[allow(unused_mut)] + fn {{{operationId}}}(&self, {{#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}}{{^-last}}, {{/-last}}{{/allParams}}) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::{{{httpMethod.toUpperCase}}}, "{{{path}}}".to_string()) {{#hasAuthMethods}} {{#authMethods}} {{#isApiKey}} @@ -68,7 +72,8 @@ impl{{{classname}}} for {{{classname}}}Client { {{/required}} {{^required}} if let Some(ref s) = {{{paramName}}} { - req = req.with_query_param("{{{baseName}}}".to_string(), s{{#isArray}}.join(","){{/isArray}}.to_string()); + let query_value = {{#isArray}}s.iter().map(|s| s.to_string()).collect::>().join(","){{/isArray}}{{^isArray}}s.to_string(){{/isArray}}; + req = req.with_query_param("{{{baseName}}}".to_string(), query_value); } {{/required}} {{/queryParams}} diff --git a/modules/openapi-generator/src/main/resources/rust/hyper/api_mod.mustache b/modules/openapi-generator/src/main/resources/rust/hyper/api_mod.mustache index 4f220c93d56..8314cb60b07 100644 --- a/modules/openapi-generator/src/main/resources/rust/hyper/api_mod.mustache +++ b/modules/openapi-generator/src/main/resources/rust/hyper/api_mod.mustache @@ -1,49 +1,45 @@ +use http; use hyper; -use serde; use serde_json; #[derive(Debug)] -pub enum Error { - UriError(hyper::error::UriError), +pub enum Error { + Api(ApiError), + Header(hyper::http::header::InvalidHeaderValue), + Http(http::Error), Hyper(hyper::Error), Serde(serde_json::Error), - ApiError(ApiError), + UriError(http::uri::InvalidUri), } #[derive(Debug)] -pub struct ApiError { +pub struct ApiError { pub code: hyper::StatusCode, - pub content: Option, + pub body: hyper::body::Body, } -impl<'de, T> From<(hyper::StatusCode, &'de [u8])> for Error - where T: serde::Deserialize<'de> { - fn from(e: (hyper::StatusCode, &'de [u8])) -> Self { - if e.1.len() == 0 { - return Error::ApiError(ApiError{ - code: e.0, - content: None, - }); - } - match serde_json::from_slice::(e.1) { - Ok(t) => Error::ApiError(ApiError{ - code: e.0, - content: Some(t), - }), - Err(e) => { - Error::from(e) - } - } +impl From<(hyper::StatusCode, hyper::body::Body)> for Error { + fn from(e: (hyper::StatusCode, hyper::body::Body)) -> Self { + Error::Api(ApiError { + code: e.0, + body: e.1, + }) } } -impl From for Error { +impl From for Error { + fn from(e: http::Error) -> Self { + return Error::Http(e) + } +} + +impl From for Error { fn from(e: hyper::Error) -> Self { return Error::Hyper(e) } } -impl From for Error { +impl From for Error { fn from(e: serde_json::Error) -> Self { return Error::Serde(e) } diff --git a/modules/openapi-generator/src/main/resources/rust/hyper/client.mustache b/modules/openapi-generator/src/main/resources/rust/hyper/client.mustache index 5b3bcf85c75..25124d94b36 100644 --- a/modules/openapi-generator/src/main/resources/rust/hyper/client.mustache +++ b/modules/openapi-generator/src/main/resources/rust/hyper/client.mustache @@ -18,7 +18,8 @@ pub struct APIClient { } impl APIClient { - pub fn new(configuration: Configuration) -> APIClient { + pub fn new(configuration: Configuration) -> APIClient + where C: Clone + std::marker::Send + Sync + 'static { let rc = Rc::new(configuration); APIClient { diff --git a/modules/openapi-generator/src/main/resources/rust/hyper/configuration.mustache b/modules/openapi-generator/src/main/resources/rust/hyper/configuration.mustache index adb51d6e92c..ee6f407d31b 100644 --- a/modules/openapi-generator/src/main/resources/rust/hyper/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/rust/hyper/configuration.mustache @@ -1,7 +1,8 @@ {{>partial_header}} use hyper; -pub struct Configuration { +pub struct Configuration + where C: Clone + std::marker::Send + Sync + 'static { pub base_path: String, pub user_agent: Option, pub client: hyper::client::Client, @@ -18,12 +19,13 @@ pub struct ApiKey { pub key: String, } -impl Configuration { +impl Configuration + where C: Clone + std::marker::Send + Sync { pub fn new(client: hyper::client::Client) -> Configuration { Configuration { base_path: "{{{basePath}}}".to_owned(), user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, - client: client, + client, basic_auth: None, oauth_access_token: None, api_key: None, diff --git a/modules/openapi-generator/src/main/resources/rust/request.rs b/modules/openapi-generator/src/main/resources/rust/request.rs index f97b5277196..0aa51fa0c59 100644 --- a/modules/openapi-generator/src/main/resources/rust/request.rs +++ b/modules/openapi-generator/src/main/resources/rust/request.rs @@ -1,14 +1,16 @@ -use std::borrow::Cow; use std::collections::HashMap; +use std::pin::Pin; -use super::{configuration, Error}; use futures; -use futures::{Future, Stream}; +use futures::Future; +use futures::future::*; use hyper; -use hyper::header::UserAgent; +use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, USER_AGENT}; use serde; use serde_json; +use super::{configuration, Error}; + pub(crate) struct ApiKey { pub in_header: bool, pub in_query: bool, @@ -32,8 +34,11 @@ pub(crate) enum Auth { Oauth, } +/// If the authorization type is unspecified then it will be automatically detected based +/// on the configuration. This functionality is useful when the OpenAPI definition does not +/// include an authorization scheme. pub(crate) struct Request { - auth: Auth, + auth: Option, method: hyper::Method, path: String, query_params: HashMap, @@ -48,9 +53,9 @@ pub(crate) struct Request { impl Request { pub fn new(method: hyper::Method, path: String) -> Self { Request { - auth: Auth::None, - method: method, - path: path, + auth: None, + method, + path, query_params: HashMap::new(), path_params: HashMap::new(), form_params: HashMap::new(), @@ -91,24 +96,20 @@ impl Request { } pub fn with_auth(mut self, auth: Auth) -> Self { - self.auth = auth; + self.auth = Some(auth); self } pub fn execute<'a, C, U>( self, conf: &configuration::Configuration, - ) -> Box> + 'a> - where - C: hyper::client::Connect, - U: Sized + 'a, - for<'de> U: serde::Deserialize<'de>, + ) -> Pin> + 'a>> + where + C: hyper::client::connect::Connect + Clone + std::marker::Send + Sync, + U: Sized + std::marker::Send + 'a, + for<'de> U: serde::Deserialize<'de>, { let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned()); - // raw_headers is for headers we don't know the proper type of (e.g. custom api key - // headers); headers is for ones we do know the type of. - let mut raw_headers = HashMap::new(); - let mut headers: hyper::header::Headers = hyper::header::Headers::new(); let mut path = self.path; for (k, v) in self.path_params { @@ -116,46 +117,10 @@ impl Request { path = path.replace(&format!("{{{}}}", k), &v); } - for (k, v) in self.header_params { - raw_headers.insert(k, v); - } - for (key, val) in self.query_params { query_string.append_pair(&key, &val); } - match self.auth { - Auth::ApiKey(apikey) => { - if let Some(ref key) = conf.api_key { - let val = apikey.key(&key.prefix, &key.key); - if apikey.in_query { - query_string.append_pair(&apikey.param_name, &val); - } - if apikey.in_header { - raw_headers.insert(apikey.param_name, val); - } - } - } - Auth::Basic => { - if let Some(ref auth_conf) = conf.basic_auth { - let auth = hyper::header::Authorization(hyper::header::Basic { - username: auth_conf.0.to_owned(), - password: auth_conf.1.to_owned(), - }); - headers.set(auth); - } - } - Auth::Oauth => { - if let Some(ref token) = conf.oauth_access_token { - let auth = hyper::header::Authorization(hyper::header::Bearer { - token: token.to_owned(), - }); - headers.set(auth); - } - } - Auth::None => {} - } - let mut uri_str = format!("{}{}", conf.base_path, path); let query_string_str = query_string.finish(); @@ -164,76 +129,110 @@ impl Request { uri_str += &query_string_str; } let uri: hyper::Uri = match uri_str.parse() { - Err(e) => { - return Box::new(futures::future::err(Error::UriError(e))); - } + Err(e) => return Box::pin(futures::future::err(Error::UriError(e))), Ok(u) => u, }; - let mut req = hyper::Request::new(self.method, uri); - { - let req_headers = req.headers_mut(); - if let Some(ref user_agent) = conf.user_agent { - req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone()))); - } + let mut req_builder = hyper::Request::builder() + .uri(uri) + .method(self.method); - req_headers.extend(headers.iter()); - - for (key, val) in raw_headers { - req_headers.set_raw(key, val); + // Detect the authorization type if it hasn't been set. + let auth = self.auth.unwrap_or_else(|| + if conf.api_key.is_some() { + panic!("Cannot automatically set the API key from the configuration, it must be specified in the OpenAPI definition") + } else if conf.oauth_access_token.is_some() { + Auth::Oauth + } else if conf.basic_auth.is_some() { + Auth::Basic + } else { + Auth::None } + ); + match auth { + Auth::ApiKey(apikey) => { + if let Some(ref key) = conf.api_key { + let val = apikey.key(&key.prefix, &key.key); + if apikey.in_query { + query_string.append_pair(&apikey.param_name, &val); + } + if apikey.in_header { + req_builder = req_builder.header(&apikey.param_name, val); + } + } + } + Auth::Basic => { + if let Some(ref auth_conf) = conf.basic_auth { + let mut text = auth_conf.0.clone(); + text.push(':'); + if let Some(ref pass) = auth_conf.1 { + text.push_str(&pass[..]); + } + let encoded = base64::encode(&text); + req_builder = req_builder.header(AUTHORIZATION, encoded); + } + } + Auth::Oauth => { + if let Some(ref token) = conf.oauth_access_token { + let text = "Bearer ".to_owned() + token; + req_builder = req_builder.header(AUTHORIZATION, text); + } + } + Auth::None => {} } - if self.form_params.len() > 0 { - req.headers_mut().set(hyper::header::ContentType::form_url_encoded()); + if let Some(ref user_agent) = conf.user_agent { + req_builder = req_builder.header(USER_AGENT, match HeaderValue::from_str(user_agent) { + Ok(header_value) => header_value, + Err(e) => return Box::pin(futures::future::err(super::Error::Header(e))) + }); + } + + for (k, v) in self.header_params { + req_builder = req_builder.header(&k, v); + } + + let req_headers = req_builder.headers_mut().unwrap(); + let request_result = if self.form_params.len() > 0 { + req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/ x-www-form-urlencoded")); let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned()); for (k, v) in self.form_params { enc.append_pair(&k, &v); } - req.set_body(enc.finish()); - } + req_builder.body(hyper::Body::from(enc.finish())) + } else if let Some(body) = self.serialized_body { + req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + req_headers.insert(CONTENT_LENGTH, body.len().into()); + req_builder.body(hyper::Body::from(body)) + } else { + req_builder.body(hyper::Body::default()) + }; + let request = match request_result { + Ok(request) => request, + Err(e) => return Box::pin(futures::future::err(Error::from(e))) + }; - if let Some(body) = self.serialized_body { - req.headers_mut().set(hyper::header::ContentType::json()); - req.headers_mut() - .set(hyper::header::ContentLength(body.len() as u64)); - req.set_body(body); - } - - let no_ret_type = self.no_return_type; - let res = conf.client - .request(req) - .map_err(|e| Error::from(e)) - .and_then(|resp| { - let status = resp.status(); - resp.body() - .concat2() - .and_then(move |body| Ok((status, body))) - .map_err(|e| Error::from(e)) - }) - .and_then(|(status, body)| { - if status.is_success() { - Ok(body) - } else { - Err(Error::from((status, &*body))) - } - }); - Box::new( - res - .and_then(move |body| { - let parsed: Result = if no_ret_type { - // This is a hack; if there's no_ret_type, U is (), but serde_json gives an - // error when deserializing "" into (), so deserialize 'null' into it - // instead. - // An alternate option would be to require U: Default, and then return - // U::default() here instead since () implements that, but then we'd - // need to impl default for all models. - serde_json::from_str("null") - } else { - serde_json::from_slice(&body) - }; - parsed.map_err(|e| Error::from(e)) - }) - ) + let no_return_type = self.no_return_type; + Box::pin(conf.client + .request(request) + .map_err(|e| Error::from(e)) + .and_then(move |response| { + let status = response.status(); + if !status.is_success() { + futures::future::err::(Error::from((status, response.into_body()))).boxed() + } else if no_return_type { + // This is a hack; if there's no_ret_type, U is (), but serde_json gives an + // error when deserializing "" into (), so deserialize 'null' into it + // instead. + // An alternate option would be to require U: Default, and then return + // U::default() here instead since () implements that, but then we'd + // need to impl default for all models. + futures::future::ok::(serde_json::from_str("null").expect("serde null value")).boxed() + } else { + hyper::body::to_bytes(response.into_body()) + .map(|bytes| serde_json::from_slice(&bytes.unwrap())) + .map_err(|e| Error::from(e)).boxed() + } + })) } } diff --git a/samples/client/petstore/rust/hyper/petstore/Cargo.toml b/samples/client/petstore/rust/hyper/petstore/Cargo.toml index 4bed4953a55..443de5b186a 100644 --- a/samples/client/petstore/rust/hyper/petstore/Cargo.toml +++ b/samples/client/petstore/rust/hyper/petstore/Cargo.toml @@ -9,10 +9,12 @@ serde = "^1.0" serde_derive = "^1.0" serde_json = "^1.0" url = "^2.2" -hyper = "~0.11" +hyper = { version = "~0.14", features = ["full"] } +hyper-tls = "~0.5" +http = "~0.2" serde_yaml = "0.7" base64 = "~0.7.0" -futures = "0.1.23" +futures = "^0.3" [dev-dependencies] tokio-core = "*" diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/client.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/client.rs index 34953d4a063..290b99e86f3 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/client.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/client.rs @@ -10,7 +10,8 @@ pub struct APIClient { } impl APIClient { - pub fn new(configuration: Configuration) -> APIClient { + pub fn new(configuration: Configuration) -> APIClient + where C: Clone + std::marker::Send + Sync + 'static { let rc = Rc::new(configuration); APIClient { diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/configuration.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/configuration.rs index 83d5f1c3d0c..ae41a752976 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/configuration.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/configuration.rs @@ -10,7 +10,8 @@ use hyper; -pub struct Configuration { +pub struct Configuration + where C: Clone + std::marker::Send + Sync + 'static { pub base_path: String, pub user_agent: Option, pub client: hyper::client::Client, @@ -27,12 +28,13 @@ pub struct ApiKey { pub key: String, } -impl Configuration { +impl Configuration + where C: Clone + std::marker::Send + Sync { pub fn new(client: hyper::client::Client) -> Configuration { Configuration { base_path: "http://petstore.swagger.io/v2".to_owned(), user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), - client: client, + client, basic_auth: None, oauth_access_token: None, api_key: None, diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/mod.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/mod.rs index c9d96c29fd0..1245257e5d8 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/mod.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/mod.rs @@ -1,49 +1,45 @@ +use http; use hyper; -use serde; use serde_json; #[derive(Debug)] -pub enum Error { - UriError(hyper::error::UriError), +pub enum Error { + Api(ApiError), + Header(hyper::http::header::InvalidHeaderValue), + Http(http::Error), Hyper(hyper::Error), Serde(serde_json::Error), - ApiError(ApiError), + UriError(http::uri::InvalidUri), } #[derive(Debug)] -pub struct ApiError { +pub struct ApiError { pub code: hyper::StatusCode, - pub content: Option, + pub body: hyper::body::Body, } -impl<'de, T> From<(hyper::StatusCode, &'de [u8])> for Error - where T: serde::Deserialize<'de> { - fn from(e: (hyper::StatusCode, &'de [u8])) -> Self { - if e.1.len() == 0 { - return Error::ApiError(ApiError{ - code: e.0, - content: None, - }); - } - match serde_json::from_slice::(e.1) { - Ok(t) => Error::ApiError(ApiError{ - code: e.0, - content: Some(t), - }), - Err(e) => { - Error::from(e) - } - } +impl From<(hyper::StatusCode, hyper::body::Body)> for Error { + fn from(e: (hyper::StatusCode, hyper::body::Body)) -> Self { + Error::Api(ApiError { + code: e.0, + body: e.1, + }) } } -impl From for Error { +impl From for Error { + fn from(e: http::Error) -> Self { + return Error::Http(e) + } +} + +impl From for Error { fn from(e: hyper::Error) -> Self { return Error::Hyper(e) } } -impl From for Error { +impl From for Error { fn from(e: serde_json::Error) -> Self { return Error::Serde(e) } diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/pet_api.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/pet_api.rs index f1bdaf0e89a..3d90eae36b3 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/pet_api.rs @@ -4,27 +4,29 @@ * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 - * + * * Generated by: https://openapi-generator.tech */ use std::rc::Rc; use std::borrow::Borrow; +use std::pin::Pin; #[allow(unused_imports)] use std::option::Option; use hyper; -use serde_json; use futures::Future; use super::{Error, configuration}; use super::request as __internal_request; -pub struct PetApiClient { +pub struct PetApiClient + where C: Clone + std::marker::Send + Sync + 'static { configuration: Rc>, } -impl PetApiClient { +impl PetApiClient + where C: Clone + std::marker::Send + Sync { pub fn new(configuration: Rc>) -> PetApiClient { PetApiClient { configuration, @@ -33,19 +35,21 @@ impl PetApiClient { } pub trait PetApi { - fn add_pet(&self, pet: crate::models::Pet) -> Box>>; - fn delete_pet(&self, pet_id: i64, api_key: Option<&str>) -> Box>>; - fn find_pets_by_status(&self, status: Vec) -> Box, Error = Error>>; - fn find_pets_by_tags(&self, tags: Vec) -> Box, Error = Error>>; - fn get_pet_by_id(&self, pet_id: i64) -> Box>>; - fn update_pet(&self, pet: crate::models::Pet) -> Box>>; - fn update_pet_with_form(&self, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Box>>; - fn upload_file(&self, pet_id: i64, additional_metadata: Option<&str>, file: Option) -> Box>>; + fn add_pet(&self, body: crate::models::Pet) -> Pin>>>; + fn delete_pet(&self, pet_id: i64, api_key: Option<&str>) -> Pin>>>; + fn find_pets_by_status(&self, status: Vec) -> Pin, Error>>>>; + fn find_pets_by_tags(&self, tags: Vec) -> Pin, Error>>>>; + fn get_pet_by_id(&self, pet_id: i64) -> Pin>>>; + fn update_pet(&self, body: crate::models::Pet) -> Pin>>>; + fn update_pet_with_form(&self, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Pin>>>; + fn upload_file(&self, pet_id: i64, additional_metadata: Option<&str>, file: Option) -> Pin>>>; } -implPetApi for PetApiClient { - fn add_pet(&self, pet: crate::models::Pet) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Post, "/pet".to_string()) +implPetApi for PetApiClient + where C: Clone + std::marker::Send + Sync { + #[allow(unused_mut)] + fn add_pet(&self, body: crate::models::Pet) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::POST, "/pet".to_string()) .with_auth(__internal_request::Auth::Oauth) ; req = req.with_body_param(pet); @@ -53,8 +57,9 @@ implPetApi for PetApiClient { req.execute(self.configuration.borrow()) } - fn delete_pet(&self, pet_id: i64, api_key: Option<&str>) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Delete, "/pet/{petId}".to_string()) + #[allow(unused_mut)] + fn delete_pet(&self, pet_id: i64, api_key: Option<&str>) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::DELETE, "/pet/{petId}".to_string()) .with_auth(__internal_request::Auth::Oauth) ; req = req.with_path_param("petId".to_string(), pet_id.to_string()); @@ -66,8 +71,9 @@ implPetApi for PetApiClient { req.execute(self.configuration.borrow()) } - fn find_pets_by_status(&self, status: Vec) -> Box, Error = Error>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/pet/findByStatus".to_string()) + #[allow(unused_mut)] + fn find_pets_by_status(&self, status: Vec) -> Pin, Error>>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/pet/findByStatus".to_string()) .with_auth(__internal_request::Auth::Oauth) ; req = req.with_query_param("status".to_string(), status.join(",").to_string()); @@ -75,8 +81,9 @@ implPetApi for PetApiClient { req.execute(self.configuration.borrow()) } - fn find_pets_by_tags(&self, tags: Vec) -> Box, Error = Error>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/pet/findByTags".to_string()) + #[allow(unused_mut)] + fn find_pets_by_tags(&self, tags: Vec) -> Pin, Error>>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/pet/findByTags".to_string()) .with_auth(__internal_request::Auth::Oauth) ; req = req.with_query_param("tags".to_string(), tags.join(",").to_string()); @@ -84,8 +91,9 @@ implPetApi for PetApiClient { req.execute(self.configuration.borrow()) } - fn get_pet_by_id(&self, pet_id: i64) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/pet/{petId}".to_string()) + #[allow(unused_mut)] + fn get_pet_by_id(&self, pet_id: i64) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/pet/{petId}".to_string()) .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ in_header: true, in_query: false, @@ -97,8 +105,9 @@ implPetApi for PetApiClient { req.execute(self.configuration.borrow()) } - fn update_pet(&self, pet: crate::models::Pet) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Put, "/pet".to_string()) + #[allow(unused_mut)] + fn update_pet(&self, body: crate::models::Pet) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::PUT, "/pet".to_string()) .with_auth(__internal_request::Auth::Oauth) ; req = req.with_body_param(pet); @@ -106,8 +115,9 @@ implPetApi for PetApiClient { req.execute(self.configuration.borrow()) } - fn update_pet_with_form(&self, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Post, "/pet/{petId}".to_string()) + #[allow(unused_mut)] + fn update_pet_with_form(&self, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::POST, "/pet/{petId}".to_string()) .with_auth(__internal_request::Auth::Oauth) ; req = req.with_path_param("petId".to_string(), pet_id.to_string()); @@ -122,8 +132,9 @@ implPetApi for PetApiClient { req.execute(self.configuration.borrow()) } - fn upload_file(&self, pet_id: i64, additional_metadata: Option<&str>, file: Option) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Post, "/pet/{petId}/uploadImage".to_string()) + #[allow(unused_mut)] + fn upload_file(&self, pet_id: i64, additional_metadata: Option<&str>, file: Option) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::POST, "/pet/{petId}/uploadImage".to_string()) .with_auth(__internal_request::Auth::Oauth) ; req = req.with_path_param("petId".to_string(), pet_id.to_string()); diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/request.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/request.rs index f97b5277196..0aa51fa0c59 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/request.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/request.rs @@ -1,14 +1,16 @@ -use std::borrow::Cow; use std::collections::HashMap; +use std::pin::Pin; -use super::{configuration, Error}; use futures; -use futures::{Future, Stream}; +use futures::Future; +use futures::future::*; use hyper; -use hyper::header::UserAgent; +use hyper::header::{AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE, HeaderValue, USER_AGENT}; use serde; use serde_json; +use super::{configuration, Error}; + pub(crate) struct ApiKey { pub in_header: bool, pub in_query: bool, @@ -32,8 +34,11 @@ pub(crate) enum Auth { Oauth, } +/// If the authorization type is unspecified then it will be automatically detected based +/// on the configuration. This functionality is useful when the OpenAPI definition does not +/// include an authorization scheme. pub(crate) struct Request { - auth: Auth, + auth: Option, method: hyper::Method, path: String, query_params: HashMap, @@ -48,9 +53,9 @@ pub(crate) struct Request { impl Request { pub fn new(method: hyper::Method, path: String) -> Self { Request { - auth: Auth::None, - method: method, - path: path, + auth: None, + method, + path, query_params: HashMap::new(), path_params: HashMap::new(), form_params: HashMap::new(), @@ -91,24 +96,20 @@ impl Request { } pub fn with_auth(mut self, auth: Auth) -> Self { - self.auth = auth; + self.auth = Some(auth); self } pub fn execute<'a, C, U>( self, conf: &configuration::Configuration, - ) -> Box> + 'a> - where - C: hyper::client::Connect, - U: Sized + 'a, - for<'de> U: serde::Deserialize<'de>, + ) -> Pin> + 'a>> + where + C: hyper::client::connect::Connect + Clone + std::marker::Send + Sync, + U: Sized + std::marker::Send + 'a, + for<'de> U: serde::Deserialize<'de>, { let mut query_string = ::url::form_urlencoded::Serializer::new("".to_owned()); - // raw_headers is for headers we don't know the proper type of (e.g. custom api key - // headers); headers is for ones we do know the type of. - let mut raw_headers = HashMap::new(); - let mut headers: hyper::header::Headers = hyper::header::Headers::new(); let mut path = self.path; for (k, v) in self.path_params { @@ -116,46 +117,10 @@ impl Request { path = path.replace(&format!("{{{}}}", k), &v); } - for (k, v) in self.header_params { - raw_headers.insert(k, v); - } - for (key, val) in self.query_params { query_string.append_pair(&key, &val); } - match self.auth { - Auth::ApiKey(apikey) => { - if let Some(ref key) = conf.api_key { - let val = apikey.key(&key.prefix, &key.key); - if apikey.in_query { - query_string.append_pair(&apikey.param_name, &val); - } - if apikey.in_header { - raw_headers.insert(apikey.param_name, val); - } - } - } - Auth::Basic => { - if let Some(ref auth_conf) = conf.basic_auth { - let auth = hyper::header::Authorization(hyper::header::Basic { - username: auth_conf.0.to_owned(), - password: auth_conf.1.to_owned(), - }); - headers.set(auth); - } - } - Auth::Oauth => { - if let Some(ref token) = conf.oauth_access_token { - let auth = hyper::header::Authorization(hyper::header::Bearer { - token: token.to_owned(), - }); - headers.set(auth); - } - } - Auth::None => {} - } - let mut uri_str = format!("{}{}", conf.base_path, path); let query_string_str = query_string.finish(); @@ -164,76 +129,110 @@ impl Request { uri_str += &query_string_str; } let uri: hyper::Uri = match uri_str.parse() { - Err(e) => { - return Box::new(futures::future::err(Error::UriError(e))); - } + Err(e) => return Box::pin(futures::future::err(Error::UriError(e))), Ok(u) => u, }; - let mut req = hyper::Request::new(self.method, uri); - { - let req_headers = req.headers_mut(); - if let Some(ref user_agent) = conf.user_agent { - req_headers.set(UserAgent::new(Cow::Owned(user_agent.clone()))); - } + let mut req_builder = hyper::Request::builder() + .uri(uri) + .method(self.method); - req_headers.extend(headers.iter()); - - for (key, val) in raw_headers { - req_headers.set_raw(key, val); + // Detect the authorization type if it hasn't been set. + let auth = self.auth.unwrap_or_else(|| + if conf.api_key.is_some() { + panic!("Cannot automatically set the API key from the configuration, it must be specified in the OpenAPI definition") + } else if conf.oauth_access_token.is_some() { + Auth::Oauth + } else if conf.basic_auth.is_some() { + Auth::Basic + } else { + Auth::None } + ); + match auth { + Auth::ApiKey(apikey) => { + if let Some(ref key) = conf.api_key { + let val = apikey.key(&key.prefix, &key.key); + if apikey.in_query { + query_string.append_pair(&apikey.param_name, &val); + } + if apikey.in_header { + req_builder = req_builder.header(&apikey.param_name, val); + } + } + } + Auth::Basic => { + if let Some(ref auth_conf) = conf.basic_auth { + let mut text = auth_conf.0.clone(); + text.push(':'); + if let Some(ref pass) = auth_conf.1 { + text.push_str(&pass[..]); + } + let encoded = base64::encode(&text); + req_builder = req_builder.header(AUTHORIZATION, encoded); + } + } + Auth::Oauth => { + if let Some(ref token) = conf.oauth_access_token { + let text = "Bearer ".to_owned() + token; + req_builder = req_builder.header(AUTHORIZATION, text); + } + } + Auth::None => {} } - if self.form_params.len() > 0 { - req.headers_mut().set(hyper::header::ContentType::form_url_encoded()); + if let Some(ref user_agent) = conf.user_agent { + req_builder = req_builder.header(USER_AGENT, match HeaderValue::from_str(user_agent) { + Ok(header_value) => header_value, + Err(e) => return Box::pin(futures::future::err(super::Error::Header(e))) + }); + } + + for (k, v) in self.header_params { + req_builder = req_builder.header(&k, v); + } + + let req_headers = req_builder.headers_mut().unwrap(); + let request_result = if self.form_params.len() > 0 { + req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/ x-www-form-urlencoded")); let mut enc = ::url::form_urlencoded::Serializer::new("".to_owned()); for (k, v) in self.form_params { enc.append_pair(&k, &v); } - req.set_body(enc.finish()); - } + req_builder.body(hyper::Body::from(enc.finish())) + } else if let Some(body) = self.serialized_body { + req_headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json")); + req_headers.insert(CONTENT_LENGTH, body.len().into()); + req_builder.body(hyper::Body::from(body)) + } else { + req_builder.body(hyper::Body::default()) + }; + let request = match request_result { + Ok(request) => request, + Err(e) => return Box::pin(futures::future::err(Error::from(e))) + }; - if let Some(body) = self.serialized_body { - req.headers_mut().set(hyper::header::ContentType::json()); - req.headers_mut() - .set(hyper::header::ContentLength(body.len() as u64)); - req.set_body(body); - } - - let no_ret_type = self.no_return_type; - let res = conf.client - .request(req) - .map_err(|e| Error::from(e)) - .and_then(|resp| { - let status = resp.status(); - resp.body() - .concat2() - .and_then(move |body| Ok((status, body))) - .map_err(|e| Error::from(e)) - }) - .and_then(|(status, body)| { - if status.is_success() { - Ok(body) - } else { - Err(Error::from((status, &*body))) - } - }); - Box::new( - res - .and_then(move |body| { - let parsed: Result = if no_ret_type { - // This is a hack; if there's no_ret_type, U is (), but serde_json gives an - // error when deserializing "" into (), so deserialize 'null' into it - // instead. - // An alternate option would be to require U: Default, and then return - // U::default() here instead since () implements that, but then we'd - // need to impl default for all models. - serde_json::from_str("null") - } else { - serde_json::from_slice(&body) - }; - parsed.map_err(|e| Error::from(e)) - }) - ) + let no_return_type = self.no_return_type; + Box::pin(conf.client + .request(request) + .map_err(|e| Error::from(e)) + .and_then(move |response| { + let status = response.status(); + if !status.is_success() { + futures::future::err::(Error::from((status, response.into_body()))).boxed() + } else if no_return_type { + // This is a hack; if there's no_ret_type, U is (), but serde_json gives an + // error when deserializing "" into (), so deserialize 'null' into it + // instead. + // An alternate option would be to require U: Default, and then return + // U::default() here instead since () implements that, but then we'd + // need to impl default for all models. + futures::future::ok::(serde_json::from_str("null").expect("serde null value")).boxed() + } else { + hyper::body::to_bytes(response.into_body()) + .map(|bytes| serde_json::from_slice(&bytes.unwrap())) + .map_err(|e| Error::from(e)).boxed() + } + })) } } diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/store_api.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/store_api.rs index 7e5aaa33da2..303a418d696 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/store_api.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/store_api.rs @@ -4,27 +4,29 @@ * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 - * + * * Generated by: https://openapi-generator.tech */ use std::rc::Rc; use std::borrow::Borrow; +use std::pin::Pin; #[allow(unused_imports)] use std::option::Option; use hyper; -use serde_json; use futures::Future; use super::{Error, configuration}; use super::request as __internal_request; -pub struct StoreApiClient { +pub struct StoreApiClient + where C: Clone + std::marker::Send + Sync + 'static { configuration: Rc>, } -impl StoreApiClient { +impl StoreApiClient + where C: Clone + std::marker::Send + Sync { pub fn new(configuration: Rc>) -> StoreApiClient { StoreApiClient { configuration, @@ -33,15 +35,17 @@ impl StoreApiClient { } pub trait StoreApi { - fn delete_order(&self, order_id: &str) -> Box>>; - fn get_inventory(&self, ) -> Box, Error = Error>>; - fn get_order_by_id(&self, order_id: i64) -> Box>>; - fn place_order(&self, order: crate::models::Order) -> Box>>; + fn delete_order(&self, order_id: &str) -> Pin>>>; + fn get_inventory(&self, ) -> Pin, Error>>>>; + fn get_order_by_id(&self, order_id: i64) -> Pin>>>; + fn place_order(&self, body: crate::models::Order) -> Pin>>>; } -implStoreApi for StoreApiClient { - fn delete_order(&self, order_id: &str) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Delete, "/store/order/{orderId}".to_string()) +implStoreApi for StoreApiClient + where C: Clone + std::marker::Send + Sync { + #[allow(unused_mut)] + fn delete_order(&self, order_id: &str) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::DELETE, "/store/order/{orderId}".to_string()) ; req = req.with_path_param("orderId".to_string(), order_id.to_string()); req = req.returns_nothing(); @@ -49,8 +53,9 @@ implStoreApi for StoreApiClient { req.execute(self.configuration.borrow()) } - fn get_inventory(&self, ) -> Box, Error = Error>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/store/inventory".to_string()) + #[allow(unused_mut)] + fn get_inventory(&self, ) -> Pin, Error>>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/store/inventory".to_string()) .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ in_header: true, in_query: false, @@ -61,16 +66,18 @@ implStoreApi for StoreApiClient { req.execute(self.configuration.borrow()) } - fn get_order_by_id(&self, order_id: i64) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/store/order/{orderId}".to_string()) + #[allow(unused_mut)] + fn get_order_by_id(&self, order_id: i64) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/store/order/{orderId}".to_string()) ; req = req.with_path_param("orderId".to_string(), order_id.to_string()); req.execute(self.configuration.borrow()) } - fn place_order(&self, order: crate::models::Order) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Post, "/store/order".to_string()) + #[allow(unused_mut)] + fn place_order(&self, body: crate::models::Order) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::POST, "/store/order".to_string()) ; req = req.with_body_param(order); diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/user_api.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/user_api.rs index e7326d05c4d..2651e807362 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/user_api.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/user_api.rs @@ -4,27 +4,29 @@ * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 - * + * * Generated by: https://openapi-generator.tech */ use std::rc::Rc; use std::borrow::Borrow; +use std::pin::Pin; #[allow(unused_imports)] use std::option::Option; use hyper; -use serde_json; use futures::Future; use super::{Error, configuration}; use super::request as __internal_request; -pub struct UserApiClient { +pub struct UserApiClient + where C: Clone + std::marker::Send + Sync + 'static { configuration: Rc>, } -impl UserApiClient { +impl UserApiClient + where C: Clone + std::marker::Send + Sync { pub fn new(configuration: Rc>) -> UserApiClient { UserApiClient { configuration, @@ -33,24 +35,21 @@ impl UserApiClient { } pub trait UserApi { - fn create_user(&self, user: crate::models::User) -> Box>>; - fn create_users_with_array_input(&self, user: Vec) -> Box>>; - fn create_users_with_list_input(&self, user: Vec) -> Box>>; - fn delete_user(&self, username: &str) -> Box>>; - fn get_user_by_name(&self, username: &str) -> Box>>; - fn login_user(&self, username: &str, password: &str) -> Box>>; - fn logout_user(&self, ) -> Box>>; - fn update_user(&self, username: &str, user: crate::models::User) -> Box>>; + fn create_user(&self, body: crate::models::User) -> Pin>>>; + fn create_users_with_array_input(&self, body: Vec) -> Pin>>>; + fn create_users_with_list_input(&self, body: Vec) -> Pin>>>; + fn delete_user(&self, username: &str) -> Pin>>>; + fn get_user_by_name(&self, username: &str) -> Pin>>>; + fn login_user(&self, username: &str, password: &str) -> Pin>>>; + fn logout_user(&self, ) -> Pin>>>; + fn update_user(&self, username: &str, body: crate::models::User) -> Pin>>>; } -implUserApi for UserApiClient { - fn create_user(&self, user: crate::models::User) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Post, "/user".to_string()) - .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ - in_header: true, - in_query: false, - param_name: "api_key".to_owned(), - })) +implUserApi for UserApiClient + where C: Clone + std::marker::Send + Sync { + #[allow(unused_mut)] + fn create_user(&self, body: crate::models::User) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::POST, "/user".to_string()) ; req = req.with_body_param(user); req = req.returns_nothing(); @@ -58,13 +57,9 @@ implUserApi for UserApiClient { req.execute(self.configuration.borrow()) } - fn create_users_with_array_input(&self, user: Vec) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Post, "/user/createWithArray".to_string()) - .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ - in_header: true, - in_query: false, - param_name: "api_key".to_owned(), - })) + #[allow(unused_mut)] + fn create_users_with_array_input(&self, body: Vec) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::POST, "/user/createWithArray".to_string()) ; req = req.with_body_param(user); req = req.returns_nothing(); @@ -72,13 +67,9 @@ implUserApi for UserApiClient { req.execute(self.configuration.borrow()) } - fn create_users_with_list_input(&self, user: Vec) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Post, "/user/createWithList".to_string()) - .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ - in_header: true, - in_query: false, - param_name: "api_key".to_owned(), - })) + #[allow(unused_mut)] + fn create_users_with_list_input(&self, body: Vec) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::POST, "/user/createWithList".to_string()) ; req = req.with_body_param(user); req = req.returns_nothing(); @@ -86,13 +77,9 @@ implUserApi for UserApiClient { req.execute(self.configuration.borrow()) } - fn delete_user(&self, username: &str) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Delete, "/user/{username}".to_string()) - .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ - in_header: true, - in_query: false, - param_name: "api_key".to_owned(), - })) + #[allow(unused_mut)] + fn delete_user(&self, username: &str) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::DELETE, "/user/{username}".to_string()) ; req = req.with_path_param("username".to_string(), username.to_string()); req = req.returns_nothing(); @@ -100,16 +87,18 @@ implUserApi for UserApiClient { req.execute(self.configuration.borrow()) } - fn get_user_by_name(&self, username: &str) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/user/{username}".to_string()) + #[allow(unused_mut)] + fn get_user_by_name(&self, username: &str) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/user/{username}".to_string()) ; req = req.with_path_param("username".to_string(), username.to_string()); req.execute(self.configuration.borrow()) } - fn login_user(&self, username: &str, password: &str) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/user/login".to_string()) + #[allow(unused_mut)] + fn login_user(&self, username: &str, password: &str) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/user/login".to_string()) ; req = req.with_query_param("username".to_string(), username.to_string()); req = req.with_query_param("password".to_string(), password.to_string()); @@ -117,26 +106,18 @@ implUserApi for UserApiClient { req.execute(self.configuration.borrow()) } - fn logout_user(&self, ) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Get, "/user/logout".to_string()) - .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ - in_header: true, - in_query: false, - param_name: "api_key".to_owned(), - })) + #[allow(unused_mut)] + fn logout_user(&self, ) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::GET, "/user/logout".to_string()) ; req = req.returns_nothing(); req.execute(self.configuration.borrow()) } - fn update_user(&self, username: &str, user: crate::models::User) -> Box>> { - let mut req = __internal_request::Request::new(hyper::Method::Put, "/user/{username}".to_string()) - .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ - in_header: true, - in_query: false, - param_name: "api_key".to_owned(), - })) + #[allow(unused_mut)] + fn update_user(&self, username: &str, body: crate::models::User) -> Pin>>> { + let mut req = __internal_request::Request::new(hyper::Method::PUT, "/user/{username}".to_string()) ; req = req.with_path_param("username".to_string(), username.to_string()); req = req.with_body_param(user); From 962e8c42178ae5445f6d60a44337a59112c4b018 Mon Sep 17 00:00:00 2001 From: WILLIAM CHENG Date: Wed, 24 Nov 2021 17:24:19 +0800 Subject: [PATCH 19/61] update samples --- .../rust/hyper/petstore/src/apis/pet_api.rs | 10 ++-- .../rust/hyper/petstore/src/apis/store_api.rs | 6 +-- .../rust/hyper/petstore/src/apis/user_api.rs | 48 +++++++++++++++---- 3 files changed, 47 insertions(+), 17 deletions(-) diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/pet_api.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/pet_api.rs index 3d90eae36b3..019ed347cdf 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/pet_api.rs @@ -4,7 +4,7 @@ * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -35,12 +35,12 @@ impl PetApiClient } pub trait PetApi { - fn add_pet(&self, body: crate::models::Pet) -> Pin>>>; + fn add_pet(&self, pet: crate::models::Pet) -> Pin>>>; fn delete_pet(&self, pet_id: i64, api_key: Option<&str>) -> Pin>>>; fn find_pets_by_status(&self, status: Vec) -> Pin, Error>>>>; fn find_pets_by_tags(&self, tags: Vec) -> Pin, Error>>>>; fn get_pet_by_id(&self, pet_id: i64) -> Pin>>>; - fn update_pet(&self, body: crate::models::Pet) -> Pin>>>; + fn update_pet(&self, pet: crate::models::Pet) -> Pin>>>; fn update_pet_with_form(&self, pet_id: i64, name: Option<&str>, status: Option<&str>) -> Pin>>>; fn upload_file(&self, pet_id: i64, additional_metadata: Option<&str>, file: Option) -> Pin>>>; } @@ -48,7 +48,7 @@ pub trait PetApi { implPetApi for PetApiClient where C: Clone + std::marker::Send + Sync { #[allow(unused_mut)] - fn add_pet(&self, body: crate::models::Pet) -> Pin>>> { + fn add_pet(&self, pet: crate::models::Pet) -> Pin>>> { let mut req = __internal_request::Request::new(hyper::Method::POST, "/pet".to_string()) .with_auth(__internal_request::Auth::Oauth) ; @@ -106,7 +106,7 @@ implPetApi for PetApiClient } #[allow(unused_mut)] - fn update_pet(&self, body: crate::models::Pet) -> Pin>>> { + fn update_pet(&self, pet: crate::models::Pet) -> Pin>>> { let mut req = __internal_request::Request::new(hyper::Method::PUT, "/pet".to_string()) .with_auth(__internal_request::Auth::Oauth) ; diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/store_api.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/store_api.rs index 303a418d696..e4bb5630828 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/store_api.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/store_api.rs @@ -4,7 +4,7 @@ * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -38,7 +38,7 @@ pub trait StoreApi { fn delete_order(&self, order_id: &str) -> Pin>>>; fn get_inventory(&self, ) -> Pin, Error>>>>; fn get_order_by_id(&self, order_id: i64) -> Pin>>>; - fn place_order(&self, body: crate::models::Order) -> Pin>>>; + fn place_order(&self, order: crate::models::Order) -> Pin>>>; } implStoreApi for StoreApiClient @@ -76,7 +76,7 @@ implStoreApi for StoreApiClient } #[allow(unused_mut)] - fn place_order(&self, body: crate::models::Order) -> Pin>>> { + fn place_order(&self, order: crate::models::Order) -> Pin>>> { let mut req = __internal_request::Request::new(hyper::Method::POST, "/store/order".to_string()) ; req = req.with_body_param(order); diff --git a/samples/client/petstore/rust/hyper/petstore/src/apis/user_api.rs b/samples/client/petstore/rust/hyper/petstore/src/apis/user_api.rs index 2651e807362..817d9166a8b 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/apis/user_api.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/apis/user_api.rs @@ -4,7 +4,7 @@ * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. * * The version of the OpenAPI document: 1.0.0 - * + * * Generated by: https://openapi-generator.tech */ @@ -35,21 +35,26 @@ impl UserApiClient } pub trait UserApi { - fn create_user(&self, body: crate::models::User) -> Pin>>>; - fn create_users_with_array_input(&self, body: Vec) -> Pin>>>; - fn create_users_with_list_input(&self, body: Vec) -> Pin>>>; + fn create_user(&self, user: crate::models::User) -> Pin>>>; + fn create_users_with_array_input(&self, user: Vec) -> Pin>>>; + fn create_users_with_list_input(&self, user: Vec) -> Pin>>>; fn delete_user(&self, username: &str) -> Pin>>>; fn get_user_by_name(&self, username: &str) -> Pin>>>; fn login_user(&self, username: &str, password: &str) -> Pin>>>; fn logout_user(&self, ) -> Pin>>>; - fn update_user(&self, username: &str, body: crate::models::User) -> Pin>>>; + fn update_user(&self, username: &str, user: crate::models::User) -> Pin>>>; } implUserApi for UserApiClient where C: Clone + std::marker::Send + Sync { #[allow(unused_mut)] - fn create_user(&self, body: crate::models::User) -> Pin>>> { + fn create_user(&self, user: crate::models::User) -> Pin>>> { let mut req = __internal_request::Request::new(hyper::Method::POST, "/user".to_string()) + .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ + in_header: true, + in_query: false, + param_name: "api_key".to_owned(), + })) ; req = req.with_body_param(user); req = req.returns_nothing(); @@ -58,8 +63,13 @@ implUserApi for UserApiClient } #[allow(unused_mut)] - fn create_users_with_array_input(&self, body: Vec) -> Pin>>> { + fn create_users_with_array_input(&self, user: Vec) -> Pin>>> { let mut req = __internal_request::Request::new(hyper::Method::POST, "/user/createWithArray".to_string()) + .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ + in_header: true, + in_query: false, + param_name: "api_key".to_owned(), + })) ; req = req.with_body_param(user); req = req.returns_nothing(); @@ -68,8 +78,13 @@ implUserApi for UserApiClient } #[allow(unused_mut)] - fn create_users_with_list_input(&self, body: Vec) -> Pin>>> { + fn create_users_with_list_input(&self, user: Vec) -> Pin>>> { let mut req = __internal_request::Request::new(hyper::Method::POST, "/user/createWithList".to_string()) + .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ + in_header: true, + in_query: false, + param_name: "api_key".to_owned(), + })) ; req = req.with_body_param(user); req = req.returns_nothing(); @@ -80,6 +95,11 @@ implUserApi for UserApiClient #[allow(unused_mut)] fn delete_user(&self, username: &str) -> Pin>>> { let mut req = __internal_request::Request::new(hyper::Method::DELETE, "/user/{username}".to_string()) + .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ + in_header: true, + in_query: false, + param_name: "api_key".to_owned(), + })) ; req = req.with_path_param("username".to_string(), username.to_string()); req = req.returns_nothing(); @@ -109,6 +129,11 @@ implUserApi for UserApiClient #[allow(unused_mut)] fn logout_user(&self, ) -> Pin>>> { let mut req = __internal_request::Request::new(hyper::Method::GET, "/user/logout".to_string()) + .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ + in_header: true, + in_query: false, + param_name: "api_key".to_owned(), + })) ; req = req.returns_nothing(); @@ -116,8 +141,13 @@ implUserApi for UserApiClient } #[allow(unused_mut)] - fn update_user(&self, username: &str, body: crate::models::User) -> Pin>>> { + fn update_user(&self, username: &str, user: crate::models::User) -> Pin>>> { let mut req = __internal_request::Request::new(hyper::Method::PUT, "/user/{username}".to_string()) + .with_auth(__internal_request::Auth::ApiKey(__internal_request::ApiKey{ + in_header: true, + in_query: false, + param_name: "api_key".to_owned(), + })) ; req = req.with_path_param("username".to_string(), username.to_string()); req = req.with_body_param(user); From 375f0a5c2db06bb5d50dbcd5feca38078cd8d85b Mon Sep 17 00:00:00 2001 From: Hui Yu Date: Wed, 24 Nov 2021 17:42:04 +0800 Subject: [PATCH 20/61] [C][Client] Use cpack to build deb package (#10935) --- .../languages/CLibcurlClientCodegen.java | 1 + .../C-libcurl/CMakeLists.txt.mustache | 19 +++++++++++---- .../C-libcurl/Packing.cmake.mustache | 24 +++++++++++++++++++ 3 files changed, 39 insertions(+), 5 deletions(-) create mode 100644 modules/openapi-generator/src/main/resources/C-libcurl/Packing.cmake.mustache diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java index d48d0f77489..788639ab1d7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CLibcurlClientCodegen.java @@ -323,6 +323,7 @@ public class CLibcurlClientCodegen extends DefaultCodegen implements CodegenConf // root folder supportingFiles.add(new SupportingFile("CMakeLists.txt.mustache", "", "CMakeLists.txt")); + supportingFiles.add(new SupportingFile("Packing.cmake.mustache", "", "Packing.cmake")); supportingFiles.add(new SupportingFile("libcurl.licence.mustache", "", "libcurl.licence")); supportingFiles.add(new SupportingFile("uncrustify-rules.cfg.mustache", "", "uncrustify-rules.cfg")); supportingFiles.add(new SupportingFile("README.md.mustache", "", "README.md")); diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/CMakeLists.txt.mustache index 7ff01b17c0e..8d2ef17609c 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/CMakeLists.txt.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/CMakeLists.txt.mustache @@ -28,7 +28,11 @@ else() endif() set(pkgName "{{projectName}}") -set(VERSION 0.0.1) # this default version can be overridden in PreTarget.cmake + +# this default version can be overridden in PreTarget.cmake +set(PROJECT_VERSION_MAJOR 0) +set(PROJECT_VERSION_MINOR 0) +set(PROJECT_VERSION_PATCH 1) find_package(CURL 7.58.0 REQUIRED) if(CURL_FOUND) @@ -84,6 +88,8 @@ set(HDRS include(PreTarget.cmake OPTIONAL) +set(PROJECT_VERSION_STRING "${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}") + # Add library with project file with project name as library name add_library(${pkgName} ${SRCS} ${HDRS}) # Link dependent libraries @@ -100,22 +106,22 @@ include(PostTarget.cmake OPTIONAL) # installation of libraries, headers, and config files if (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in) - install(TARGETS ${pkgName} DESTINATION ${CMAKE_INSTALL_PREFIX}) + install(TARGETS ${pkgName} DESTINATION lib) else() include(GNUInstallDirs) - install(TARGETS ${pkgName} DESTINATION ${CMAKE_INSTALL_PREFIX} EXPORT ${pkgName}Targets) + install(TARGETS ${pkgName} DESTINATION lib EXPORT ${pkgName}Targets) foreach(HDR_FILE ${HDRS}) get_filename_component(HDR_DIRECTORY ${HDR_FILE} DIRECTORY) get_filename_component(ABSOLUTE_HDR_DIRECTORY ${HDR_DIRECTORY} ABSOLUTE) file(RELATIVE_PATH RELATIVE_HDR_PATH ${CMAKE_CURRENT_SOURCE_DIR} ${ABSOLUTE_HDR_DIRECTORY}) - install(FILES ${HDR_FILE} DESTINATION include/${RELATIVE_HDR_PATH}) + install(FILES ${HDR_FILE} DESTINATION include/${pkgName}/${RELATIVE_HDR_PATH}) endforeach() include(CMakePackageConfigHelpers) write_basic_package_version_file( "${CMAKE_CURRENT_BINARY_DIR}/${pkgName}/${pkgName}ConfigVersion.cmake" - VERSION "${VERSION}" + VERSION "${PROJECT_VERSION_STRING}" COMPATIBILITY AnyNewerVersion ) @@ -147,6 +153,9 @@ else() ) endif() +# make installation packages +include(Packing.cmake OPTIONAL) + # Setting file variables to null set(SRCS "") set(HDRS "") diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/Packing.cmake.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/Packing.cmake.mustache new file mode 100644 index 00000000000..15bd4c8d5e9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/C-libcurl/Packing.cmake.mustache @@ -0,0 +1,24 @@ +set(CPACK_PACKAGE_NAME lib${pkgName}) + +set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) +set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) +set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) + +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY ${PROJECT_PACKAGE_DESCRIPTION_SUMMARY}) +set(CPACK_PACKAGE_VENDOR ${PROJECT_PACKAGE_VENDOR}) +set(CPACK_PACKAGE_CONTACT ${PROJECT_PACKAGE_CONTACT}) +set(CPACK_DEBIAN_PACKAGE_MAINTAINER ${PROJECT_PACKAGE_MAINTAINER}) + +set(CPACK_VERBATIM_VARIABLES YES) + +set(CPACK_PACKAGE_INSTALL_DIRECTORY ${CPACK_PACKAGE_NAME}) + +set(CPACK_PACKAGING_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX}) + +set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) + +set(CPACK_DEB_COMPONENT_INSTALL YES) + +set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS TRUE) + +include(CPack) \ No newline at end of file From 887fe07bc1a6cbe06128189c23c6fe536986bbb5 Mon Sep 17 00:00:00 2001 From: WILLIAM CHENG Date: Wed, 24 Nov 2021 17:47:31 +0800 Subject: [PATCH 21/61] upadte samples --- samples/client/petstore/c/.openapi-generator/FILES | 1 + 1 file changed, 1 insertion(+) diff --git a/samples/client/petstore/c/.openapi-generator/FILES b/samples/client/petstore/c/.openapi-generator/FILES index 4f49546590e..51014a47cdc 100644 --- a/samples/client/petstore/c/.openapi-generator/FILES +++ b/samples/client/petstore/c/.openapi-generator/FILES @@ -1,3 +1,4 @@ +Packing.cmake README.md api/PetAPI.c api/PetAPI.h From 1314e229f58cf056850dc912bbf55e49bcda2db8 Mon Sep 17 00:00:00 2001 From: dever4eg Date: Wed, 24 Nov 2021 16:46:41 +0200 Subject: [PATCH 22/61] Fixed http errors deserialization (#10940) * Fixed http errors deserialization I've found this bug in @kubernetes/client-node npm package. By the way, Here is the issue https://github.com/OpenAPITools/openapi-generator/issues/2924# * Update typescript-node samples with a fix of error handling * Update samples version Co-authored-by: Bogdan Onischenko --- .../main/resources/typescript-node/api-single.mustache | 6 +++--- .../client/petstore/typescript-node/default/api/petApi.ts | 8 ++++---- .../petstore/typescript-node/default/api/storeApi.ts | 6 +++--- .../petstore/typescript-node/default/api/userApi.ts | 4 ++-- samples/client/petstore/typescript-node/npm/api/petApi.ts | 8 ++++---- .../client/petstore/typescript-node/npm/api/storeApi.ts | 6 +++--- .../client/petstore/typescript-node/npm/api/userApi.ts | 4 ++-- 7 files changed, 21 insertions(+), 21 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/typescript-node/api-single.mustache b/modules/openapi-generator/src/main/resources/typescript-node/api-single.mustache index 6b7154dd6c8..43b9f074069 100644 --- a/modules/openapi-generator/src/main/resources/typescript-node/api-single.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-node/api-single.mustache @@ -266,10 +266,10 @@ export class {{classname}} { if (error) { reject(error); } else { - {{#returnType}} - body = ObjectSerializer.deserialize(body, "{{{.}}}"); - {{/returnType}} if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + {{#returnType}} + body = ObjectSerializer.deserialize(body, "{{{.}}}"); + {{/returnType}} resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); diff --git a/samples/client/petstore/typescript-node/default/api/petApi.ts b/samples/client/petstore/typescript-node/default/api/petApi.ts index 1dfd5447c6f..d518c2b66c8 100644 --- a/samples/client/petstore/typescript-node/default/api/petApi.ts +++ b/samples/client/petstore/typescript-node/default/api/petApi.ts @@ -289,8 +289,8 @@ export class PetApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Array"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Array"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -364,8 +364,8 @@ export class PetApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Array"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Array"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -436,8 +436,8 @@ export class PetApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Pet"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Pet"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -657,8 +657,8 @@ export class PetApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "ApiResponse"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "ApiResponse"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); diff --git a/samples/client/petstore/typescript-node/default/api/storeApi.ts b/samples/client/petstore/typescript-node/default/api/storeApi.ts index 500c6325664..aa66df0b98a 100644 --- a/samples/client/petstore/typescript-node/default/api/storeApi.ts +++ b/samples/client/petstore/typescript-node/default/api/storeApi.ts @@ -209,8 +209,8 @@ export class StoreApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "{ [key: string]: number; }"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "{ [key: string]: number; }"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -278,8 +278,8 @@ export class StoreApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Order"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Order"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -347,8 +347,8 @@ export class StoreApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Order"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Order"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); diff --git a/samples/client/petstore/typescript-node/default/api/userApi.ts b/samples/client/petstore/typescript-node/default/api/userApi.ts index 3a29f079eaf..ff11964e439 100644 --- a/samples/client/petstore/typescript-node/default/api/userApi.ts +++ b/samples/client/petstore/typescript-node/default/api/userApi.ts @@ -396,8 +396,8 @@ export class UserApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "User"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -478,8 +478,8 @@ export class UserApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "string"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "string"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); diff --git a/samples/client/petstore/typescript-node/npm/api/petApi.ts b/samples/client/petstore/typescript-node/npm/api/petApi.ts index 1dfd5447c6f..d518c2b66c8 100644 --- a/samples/client/petstore/typescript-node/npm/api/petApi.ts +++ b/samples/client/petstore/typescript-node/npm/api/petApi.ts @@ -289,8 +289,8 @@ export class PetApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Array"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Array"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -364,8 +364,8 @@ export class PetApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Array"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Array"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -436,8 +436,8 @@ export class PetApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Pet"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Pet"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -657,8 +657,8 @@ export class PetApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "ApiResponse"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "ApiResponse"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); diff --git a/samples/client/petstore/typescript-node/npm/api/storeApi.ts b/samples/client/petstore/typescript-node/npm/api/storeApi.ts index 500c6325664..aa66df0b98a 100644 --- a/samples/client/petstore/typescript-node/npm/api/storeApi.ts +++ b/samples/client/petstore/typescript-node/npm/api/storeApi.ts @@ -209,8 +209,8 @@ export class StoreApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "{ [key: string]: number; }"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "{ [key: string]: number; }"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -278,8 +278,8 @@ export class StoreApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Order"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Order"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -347,8 +347,8 @@ export class StoreApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "Order"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "Order"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); diff --git a/samples/client/petstore/typescript-node/npm/api/userApi.ts b/samples/client/petstore/typescript-node/npm/api/userApi.ts index 3a29f079eaf..ff11964e439 100644 --- a/samples/client/petstore/typescript-node/npm/api/userApi.ts +++ b/samples/client/petstore/typescript-node/npm/api/userApi.ts @@ -396,8 +396,8 @@ export class UserApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "User"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "User"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); @@ -478,8 +478,8 @@ export class UserApi { if (error) { reject(error); } else { - body = ObjectSerializer.deserialize(body, "string"); if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { + body = ObjectSerializer.deserialize(body, "string"); resolve({ response: response, body: body }); } else { reject(new HttpError(response, body, response.statusCode)); From 2e47f3e84c418c7b02fb1dbaccb55cf94bcb338c Mon Sep 17 00:00:00 2001 From: "Brian J. Miller" Date: Wed, 24 Nov 2021 08:48:21 -0600 Subject: [PATCH 23/61] Allows install typescript-axios client via npm from Git (#10890) --- .../src/main/resources/typescript-axios/package.mustache | 2 +- .../petstore/typescript-axios/builds/es6-target/package.json | 2 +- .../with-npm-version-and-separate-models-and-api/package.json | 2 +- .../typescript-axios/builds/with-npm-version/package.json | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache index 266e9de70b7..8fb03063464 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache @@ -15,7 +15,7 @@ "typings": "./dist/index.d.ts", "scripts": { "build": "tsc --outDir dist/", - "prepublishOnly": "npm run build" + "prepare": "npm run build" }, "dependencies": { "axios": "^0.21.4" diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/package.json b/samples/client/petstore/typescript-axios/builds/es6-target/package.json index 95c1617e37f..86412c07b3d 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/package.json +++ b/samples/client/petstore/typescript-axios/builds/es6-target/package.json @@ -15,7 +15,7 @@ "typings": "./dist/index.d.ts", "scripts": { "build": "tsc --outDir dist/", - "prepublishOnly": "npm run build" + "prepare": "npm run build" }, "dependencies": { "axios": "^0.21.4" diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json index 95c1617e37f..86412c07b3d 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json @@ -15,7 +15,7 @@ "typings": "./dist/index.d.ts", "scripts": { "build": "tsc --outDir dist/", - "prepublishOnly": "npm run build" + "prepare": "npm run build" }, "dependencies": { "axios": "^0.21.4" diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json b/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json index 95c1617e37f..86412c07b3d 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json @@ -15,7 +15,7 @@ "typings": "./dist/index.d.ts", "scripts": { "build": "tsc --outDir dist/", - "prepublishOnly": "npm run build" + "prepare": "npm run build" }, "dependencies": { "axios": "^0.21.4" From 1953e706613cdedf26eebcdfedfca8483e85f5d9 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Thu, 25 Nov 2021 13:28:33 +0800 Subject: [PATCH 24/61] [C#][netcore] minor code improvement (#10951) * minor code improvement * better code format --- .../resources/csharp-netcore/api.mustache | 53 +- .../csharp-netcore/modelGeneric.mustache | 28 +- .../src/Org.OpenAPITools/Api/MultipartApi.cs | 109 +++- .../Org.OpenAPITools/Model/InlineObject.cs | 6 +- .../Org.OpenAPITools/Model/InlineObject1.cs | 6 +- .../Org.OpenAPITools/Model/InlineObject2.cs | 10 +- .../Model/MultipartMixedMarker.cs | 6 +- .../Org.OpenAPITools/Api/AnotherFakeApi.cs | 37 +- .../src/Org.OpenAPITools/Api/DefaultApi.cs | 33 +- .../src/Org.OpenAPITools/Api/FakeApi.cs | 551 +++++++++++++----- .../Api/FakeClassnameTags123Api.cs | 37 +- .../src/Org.OpenAPITools/Api/PetApi.cs | 317 +++++++--- .../src/Org.OpenAPITools/Api/StoreApi.cs | 140 +++-- .../src/Org.OpenAPITools/Api/UserApi.cs | 300 +++++++--- .../Model/AdditionalPropertiesClass.cs | 38 +- .../src/Org.OpenAPITools/Model/Animal.cs | 14 +- .../src/Org.OpenAPITools/Model/ApiResponse.cs | 16 +- .../src/Org.OpenAPITools/Model/Apple.cs | 14 +- .../src/Org.OpenAPITools/Model/AppleReq.cs | 8 +- .../Model/ArrayOfArrayOfNumberOnly.cs | 10 +- .../Model/ArrayOfNumberOnly.cs | 10 +- .../src/Org.OpenAPITools/Model/ArrayTest.cs | 18 +- .../src/Org.OpenAPITools/Model/Banana.cs | 8 +- .../src/Org.OpenAPITools/Model/BananaReq.cs | 6 +- .../src/Org.OpenAPITools/Model/BasquePig.cs | 10 +- .../Org.OpenAPITools/Model/Capitalization.cs | 30 +- .../src/Org.OpenAPITools/Model/Cat.cs | 13 +- .../src/Org.OpenAPITools/Model/CatAllOf.cs | 8 +- .../src/Org.OpenAPITools/Model/Category.cs | 12 +- .../src/Org.OpenAPITools/Model/ChildCat.cs | 17 +- .../Org.OpenAPITools/Model/ChildCatAllOf.cs | 12 +- .../src/Org.OpenAPITools/Model/ClassModel.cs | 10 +- .../Model/ComplexQuadrilateral.cs | 14 +- .../src/Org.OpenAPITools/Model/DanishPig.cs | 10 +- .../Model/DeprecatedObject.cs | 10 +- .../src/Org.OpenAPITools/Model/Dog.cs | 15 +- .../src/Org.OpenAPITools/Model/DogAllOf.cs | 10 +- .../src/Org.OpenAPITools/Model/Drawing.cs | 18 +- .../src/Org.OpenAPITools/Model/EnumArrays.cs | 10 +- .../src/Org.OpenAPITools/Model/EnumTest.cs | 24 +- .../Model/EquilateralTriangle.cs | 14 +- .../src/Org.OpenAPITools/Model/File.cs | 10 +- .../Model/FileSchemaTestClass.cs | 14 +- .../src/Org.OpenAPITools/Model/Foo.cs | 10 +- .../src/Org.OpenAPITools/Model/FormatTest.cs | 80 ++- .../Model/GrandparentAnimal.cs | 10 +- .../Org.OpenAPITools/Model/HasOnlyReadOnly.cs | 14 +- .../Model/HealthCheckResult.cs | 10 +- .../Model/InlineResponseDefault.cs | 10 +- .../Model/IsoscelesTriangle.cs | 10 +- .../src/Org.OpenAPITools/Model/List.cs | 10 +- .../src/Org.OpenAPITools/Model/MapTest.cs | 20 +- ...dPropertiesAndAdditionalPropertiesClass.cs | 18 +- .../Model/Model200Response.cs | 12 +- .../src/Org.OpenAPITools/Model/ModelClient.cs | 10 +- .../src/Org.OpenAPITools/Model/Name.cs | 16 +- .../Org.OpenAPITools/Model/NullableClass.cs | 50 +- .../src/Org.OpenAPITools/Model/NumberOnly.cs | 8 +- .../Model/ObjectWithDeprecatedFields.cs | 20 +- .../src/Org.OpenAPITools/Model/Order.cs | 20 +- .../Org.OpenAPITools/Model/OuterComposite.cs | 14 +- .../src/Org.OpenAPITools/Model/ParentPet.cs | 11 +- .../src/Org.OpenAPITools/Model/Pet.cs | 26 +- .../Model/QuadrilateralInterface.cs | 10 +- .../Org.OpenAPITools/Model/ReadOnlyFirst.cs | 14 +- .../src/Org.OpenAPITools/Model/Return.cs | 8 +- .../Org.OpenAPITools/Model/ScaleneTriangle.cs | 14 +- .../Org.OpenAPITools/Model/ShapeInterface.cs | 10 +- .../Model/SimpleQuadrilateral.cs | 14 +- .../Model/SpecialModelName.cs | 12 +- .../src/Org.OpenAPITools/Model/Tag.cs | 12 +- .../Model/TriangleInterface.cs | 10 +- .../src/Org.OpenAPITools/Model/User.cs | 50 +- .../src/Org.OpenAPITools/Model/Whale.cs | 14 +- .../src/Org.OpenAPITools/Model/Zebra.cs | 12 +- .../Model/AdditionalPropertiesClass.cs | 38 +- .../src/Org.OpenAPITools/Model/Animal.cs | 14 +- .../src/Org.OpenAPITools/Model/ApiResponse.cs | 16 +- .../src/Org.OpenAPITools/Model/Apple.cs | 14 +- .../src/Org.OpenAPITools/Model/AppleReq.cs | 8 +- .../Model/ArrayOfArrayOfNumberOnly.cs | 10 +- .../Model/ArrayOfNumberOnly.cs | 10 +- .../src/Org.OpenAPITools/Model/ArrayTest.cs | 18 +- .../src/Org.OpenAPITools/Model/Banana.cs | 8 +- .../src/Org.OpenAPITools/Model/BananaReq.cs | 6 +- .../src/Org.OpenAPITools/Model/BasquePig.cs | 10 +- .../Org.OpenAPITools/Model/Capitalization.cs | 30 +- .../src/Org.OpenAPITools/Model/Cat.cs | 13 +- .../src/Org.OpenAPITools/Model/CatAllOf.cs | 8 +- .../src/Org.OpenAPITools/Model/Category.cs | 12 +- .../src/Org.OpenAPITools/Model/ChildCat.cs | 17 +- .../Org.OpenAPITools/Model/ChildCatAllOf.cs | 12 +- .../src/Org.OpenAPITools/Model/ClassModel.cs | 10 +- .../Model/ComplexQuadrilateral.cs | 14 +- .../src/Org.OpenAPITools/Model/DanishPig.cs | 10 +- .../Model/DeprecatedObject.cs | 10 +- .../src/Org.OpenAPITools/Model/Dog.cs | 15 +- .../src/Org.OpenAPITools/Model/DogAllOf.cs | 10 +- .../src/Org.OpenAPITools/Model/Drawing.cs | 18 +- .../src/Org.OpenAPITools/Model/EnumArrays.cs | 10 +- .../src/Org.OpenAPITools/Model/EnumTest.cs | 24 +- .../Model/EquilateralTriangle.cs | 14 +- .../src/Org.OpenAPITools/Model/File.cs | 10 +- .../Model/FileSchemaTestClass.cs | 14 +- .../src/Org.OpenAPITools/Model/Foo.cs | 10 +- .../src/Org.OpenAPITools/Model/FormatTest.cs | 80 ++- .../Model/GrandparentAnimal.cs | 10 +- .../Org.OpenAPITools/Model/HasOnlyReadOnly.cs | 14 +- .../Model/HealthCheckResult.cs | 10 +- .../Model/InlineResponseDefault.cs | 10 +- .../Model/IsoscelesTriangle.cs | 10 +- .../src/Org.OpenAPITools/Model/List.cs | 10 +- .../src/Org.OpenAPITools/Model/MapTest.cs | 20 +- ...dPropertiesAndAdditionalPropertiesClass.cs | 18 +- .../Model/Model200Response.cs | 12 +- .../src/Org.OpenAPITools/Model/ModelClient.cs | 10 +- .../src/Org.OpenAPITools/Model/Name.cs | 16 +- .../Org.OpenAPITools/Model/NullableClass.cs | 50 +- .../src/Org.OpenAPITools/Model/NumberOnly.cs | 8 +- .../Model/ObjectWithDeprecatedFields.cs | 20 +- .../src/Org.OpenAPITools/Model/Order.cs | 20 +- .../Org.OpenAPITools/Model/OuterComposite.cs | 14 +- .../src/Org.OpenAPITools/Model/ParentPet.cs | 11 +- .../src/Org.OpenAPITools/Model/Pet.cs | 26 +- .../Model/QuadrilateralInterface.cs | 10 +- .../Org.OpenAPITools/Model/ReadOnlyFirst.cs | 14 +- .../src/Org.OpenAPITools/Model/Return.cs | 8 +- .../Org.OpenAPITools/Model/ScaleneTriangle.cs | 14 +- .../Org.OpenAPITools/Model/ShapeInterface.cs | 10 +- .../Model/SimpleQuadrilateral.cs | 14 +- .../Model/SpecialModelName.cs | 12 +- .../src/Org.OpenAPITools/Model/Tag.cs | 12 +- .../Model/TriangleInterface.cs | 10 +- .../src/Org.OpenAPITools/Model/User.cs | 50 +- .../src/Org.OpenAPITools/Model/Whale.cs | 14 +- .../src/Org.OpenAPITools/Model/Zebra.cs | 12 +- .../Org.OpenAPITools/Api/AnotherFakeApi.cs | 37 +- .../src/Org.OpenAPITools/Api/DefaultApi.cs | 33 +- .../src/Org.OpenAPITools/Api/FakeApi.cs | 551 +++++++++++++----- .../Api/FakeClassnameTags123Api.cs | 37 +- .../src/Org.OpenAPITools/Api/PetApi.cs | 317 +++++++--- .../src/Org.OpenAPITools/Api/StoreApi.cs | 140 +++-- .../src/Org.OpenAPITools/Api/UserApi.cs | 300 +++++++--- .../Model/AdditionalPropertiesClass.cs | 38 +- .../src/Org.OpenAPITools/Model/Animal.cs | 14 +- .../src/Org.OpenAPITools/Model/ApiResponse.cs | 16 +- .../src/Org.OpenAPITools/Model/Apple.cs | 14 +- .../src/Org.OpenAPITools/Model/AppleReq.cs | 8 +- .../Model/ArrayOfArrayOfNumberOnly.cs | 10 +- .../Model/ArrayOfNumberOnly.cs | 10 +- .../src/Org.OpenAPITools/Model/ArrayTest.cs | 18 +- .../src/Org.OpenAPITools/Model/Banana.cs | 8 +- .../src/Org.OpenAPITools/Model/BananaReq.cs | 6 +- .../src/Org.OpenAPITools/Model/BasquePig.cs | 10 +- .../Org.OpenAPITools/Model/Capitalization.cs | 30 +- .../src/Org.OpenAPITools/Model/Cat.cs | 13 +- .../src/Org.OpenAPITools/Model/CatAllOf.cs | 8 +- .../src/Org.OpenAPITools/Model/Category.cs | 12 +- .../src/Org.OpenAPITools/Model/ChildCat.cs | 17 +- .../Org.OpenAPITools/Model/ChildCatAllOf.cs | 12 +- .../src/Org.OpenAPITools/Model/ClassModel.cs | 10 +- .../Model/ComplexQuadrilateral.cs | 14 +- .../src/Org.OpenAPITools/Model/DanishPig.cs | 10 +- .../Model/DeprecatedObject.cs | 10 +- .../src/Org.OpenAPITools/Model/Dog.cs | 15 +- .../src/Org.OpenAPITools/Model/DogAllOf.cs | 10 +- .../src/Org.OpenAPITools/Model/Drawing.cs | 18 +- .../src/Org.OpenAPITools/Model/EnumArrays.cs | 10 +- .../src/Org.OpenAPITools/Model/EnumTest.cs | 24 +- .../Model/EquilateralTriangle.cs | 14 +- .../src/Org.OpenAPITools/Model/File.cs | 10 +- .../Model/FileSchemaTestClass.cs | 14 +- .../src/Org.OpenAPITools/Model/Foo.cs | 10 +- .../src/Org.OpenAPITools/Model/FormatTest.cs | 80 ++- .../Model/GrandparentAnimal.cs | 10 +- .../Org.OpenAPITools/Model/HasOnlyReadOnly.cs | 14 +- .../Model/HealthCheckResult.cs | 10 +- .../Model/InlineResponseDefault.cs | 10 +- .../Model/IsoscelesTriangle.cs | 10 +- .../src/Org.OpenAPITools/Model/List.cs | 10 +- .../src/Org.OpenAPITools/Model/MapTest.cs | 20 +- ...dPropertiesAndAdditionalPropertiesClass.cs | 18 +- .../Model/Model200Response.cs | 12 +- .../src/Org.OpenAPITools/Model/ModelClient.cs | 10 +- .../src/Org.OpenAPITools/Model/Name.cs | 16 +- .../Org.OpenAPITools/Model/NullableClass.cs | 50 +- .../src/Org.OpenAPITools/Model/NumberOnly.cs | 8 +- .../Model/ObjectWithDeprecatedFields.cs | 20 +- .../src/Org.OpenAPITools/Model/Order.cs | 20 +- .../Org.OpenAPITools/Model/OuterComposite.cs | 14 +- .../src/Org.OpenAPITools/Model/ParentPet.cs | 11 +- .../src/Org.OpenAPITools/Model/Pet.cs | 26 +- .../Model/QuadrilateralInterface.cs | 10 +- .../Org.OpenAPITools/Model/ReadOnlyFirst.cs | 14 +- .../src/Org.OpenAPITools/Model/Return.cs | 8 +- .../Org.OpenAPITools/Model/ScaleneTriangle.cs | 14 +- .../Org.OpenAPITools/Model/ShapeInterface.cs | 10 +- .../Model/SimpleQuadrilateral.cs | 14 +- .../Model/SpecialModelName.cs | 12 +- .../src/Org.OpenAPITools/Model/Tag.cs | 12 +- .../Model/TriangleInterface.cs | 10 +- .../src/Org.OpenAPITools/Model/User.cs | 50 +- .../src/Org.OpenAPITools/Model/Whale.cs | 14 +- .../src/Org.OpenAPITools/Model/Zebra.cs | 12 +- .../Org.OpenAPITools/Api/AnotherFakeApi.cs | 37 +- .../src/Org.OpenAPITools/Api/DefaultApi.cs | 33 +- .../src/Org.OpenAPITools/Api/FakeApi.cs | 551 +++++++++++++----- .../Api/FakeClassnameTags123Api.cs | 37 +- .../src/Org.OpenAPITools/Api/PetApi.cs | 317 +++++++--- .../src/Org.OpenAPITools/Api/StoreApi.cs | 140 +++-- .../src/Org.OpenAPITools/Api/UserApi.cs | 300 +++++++--- .../Model/AdditionalPropertiesClass.cs | 38 +- .../src/Org.OpenAPITools/Model/Animal.cs | 14 +- .../src/Org.OpenAPITools/Model/ApiResponse.cs | 16 +- .../src/Org.OpenAPITools/Model/Apple.cs | 14 +- .../src/Org.OpenAPITools/Model/AppleReq.cs | 8 +- .../Model/ArrayOfArrayOfNumberOnly.cs | 10 +- .../Model/ArrayOfNumberOnly.cs | 10 +- .../src/Org.OpenAPITools/Model/ArrayTest.cs | 18 +- .../src/Org.OpenAPITools/Model/Banana.cs | 8 +- .../src/Org.OpenAPITools/Model/BananaReq.cs | 6 +- .../src/Org.OpenAPITools/Model/BasquePig.cs | 10 +- .../Org.OpenAPITools/Model/Capitalization.cs | 30 +- .../src/Org.OpenAPITools/Model/Cat.cs | 13 +- .../src/Org.OpenAPITools/Model/CatAllOf.cs | 8 +- .../src/Org.OpenAPITools/Model/Category.cs | 12 +- .../src/Org.OpenAPITools/Model/ChildCat.cs | 17 +- .../Org.OpenAPITools/Model/ChildCatAllOf.cs | 12 +- .../src/Org.OpenAPITools/Model/ClassModel.cs | 10 +- .../Model/ComplexQuadrilateral.cs | 14 +- .../src/Org.OpenAPITools/Model/DanishPig.cs | 10 +- .../Model/DeprecatedObject.cs | 10 +- .../src/Org.OpenAPITools/Model/Dog.cs | 15 +- .../src/Org.OpenAPITools/Model/DogAllOf.cs | 10 +- .../src/Org.OpenAPITools/Model/Drawing.cs | 18 +- .../src/Org.OpenAPITools/Model/EnumArrays.cs | 10 +- .../src/Org.OpenAPITools/Model/EnumTest.cs | 24 +- .../Model/EquilateralTriangle.cs | 14 +- .../src/Org.OpenAPITools/Model/File.cs | 10 +- .../Model/FileSchemaTestClass.cs | 14 +- .../src/Org.OpenAPITools/Model/Foo.cs | 10 +- .../src/Org.OpenAPITools/Model/FormatTest.cs | 80 ++- .../Model/GrandparentAnimal.cs | 10 +- .../Org.OpenAPITools/Model/HasOnlyReadOnly.cs | 14 +- .../Model/HealthCheckResult.cs | 10 +- .../Model/InlineResponseDefault.cs | 10 +- .../Model/IsoscelesTriangle.cs | 10 +- .../src/Org.OpenAPITools/Model/List.cs | 10 +- .../src/Org.OpenAPITools/Model/MapTest.cs | 20 +- ...dPropertiesAndAdditionalPropertiesClass.cs | 18 +- .../Model/Model200Response.cs | 12 +- .../src/Org.OpenAPITools/Model/ModelClient.cs | 10 +- .../src/Org.OpenAPITools/Model/Name.cs | 16 +- .../Org.OpenAPITools/Model/NullableClass.cs | 50 +- .../src/Org.OpenAPITools/Model/NumberOnly.cs | 8 +- .../Model/ObjectWithDeprecatedFields.cs | 20 +- .../src/Org.OpenAPITools/Model/Order.cs | 20 +- .../Org.OpenAPITools/Model/OuterComposite.cs | 14 +- .../src/Org.OpenAPITools/Model/ParentPet.cs | 11 +- .../src/Org.OpenAPITools/Model/Pet.cs | 26 +- .../Model/QuadrilateralInterface.cs | 10 +- .../Org.OpenAPITools/Model/ReadOnlyFirst.cs | 14 +- .../src/Org.OpenAPITools/Model/Return.cs | 8 +- .../Org.OpenAPITools/Model/ScaleneTriangle.cs | 14 +- .../Org.OpenAPITools/Model/ShapeInterface.cs | 10 +- .../Model/SimpleQuadrilateral.cs | 14 +- .../Model/SpecialModelName.cs | 12 +- .../src/Org.OpenAPITools/Model/Tag.cs | 12 +- .../Model/TriangleInterface.cs | 10 +- .../src/Org.OpenAPITools/Model/User.cs | 50 +- .../src/Org.OpenAPITools/Model/Whale.cs | 14 +- .../src/Org.OpenAPITools/Model/Zebra.cs | 12 +- .../Org.OpenAPITools/Api/AnotherFakeApi.cs | 37 +- .../src/Org.OpenAPITools/Api/DefaultApi.cs | 33 +- .../src/Org.OpenAPITools/Api/FakeApi.cs | 551 +++++++++++++----- .../Api/FakeClassnameTags123Api.cs | 37 +- .../src/Org.OpenAPITools/Api/PetApi.cs | 317 +++++++--- .../src/Org.OpenAPITools/Api/StoreApi.cs | 140 +++-- .../src/Org.OpenAPITools/Api/UserApi.cs | 300 +++++++--- .../Model/AdditionalPropertiesClass.cs | 38 +- .../src/Org.OpenAPITools/Model/Animal.cs | 14 +- .../src/Org.OpenAPITools/Model/ApiResponse.cs | 16 +- .../src/Org.OpenAPITools/Model/Apple.cs | 14 +- .../src/Org.OpenAPITools/Model/AppleReq.cs | 8 +- .../Model/ArrayOfArrayOfNumberOnly.cs | 10 +- .../Model/ArrayOfNumberOnly.cs | 10 +- .../src/Org.OpenAPITools/Model/ArrayTest.cs | 18 +- .../src/Org.OpenAPITools/Model/Banana.cs | 8 +- .../src/Org.OpenAPITools/Model/BananaReq.cs | 6 +- .../src/Org.OpenAPITools/Model/BasquePig.cs | 10 +- .../Org.OpenAPITools/Model/Capitalization.cs | 30 +- .../src/Org.OpenAPITools/Model/Cat.cs | 13 +- .../src/Org.OpenAPITools/Model/CatAllOf.cs | 8 +- .../src/Org.OpenAPITools/Model/Category.cs | 12 +- .../src/Org.OpenAPITools/Model/ChildCat.cs | 17 +- .../Org.OpenAPITools/Model/ChildCatAllOf.cs | 12 +- .../src/Org.OpenAPITools/Model/ClassModel.cs | 10 +- .../Model/ComplexQuadrilateral.cs | 14 +- .../src/Org.OpenAPITools/Model/DanishPig.cs | 10 +- .../Model/DeprecatedObject.cs | 10 +- .../src/Org.OpenAPITools/Model/Dog.cs | 15 +- .../src/Org.OpenAPITools/Model/DogAllOf.cs | 10 +- .../src/Org.OpenAPITools/Model/Drawing.cs | 18 +- .../src/Org.OpenAPITools/Model/EnumArrays.cs | 10 +- .../src/Org.OpenAPITools/Model/EnumTest.cs | 24 +- .../Model/EquilateralTriangle.cs | 14 +- .../src/Org.OpenAPITools/Model/File.cs | 10 +- .../Model/FileSchemaTestClass.cs | 14 +- .../src/Org.OpenAPITools/Model/Foo.cs | 10 +- .../src/Org.OpenAPITools/Model/FormatTest.cs | 80 ++- .../Model/GrandparentAnimal.cs | 10 +- .../Org.OpenAPITools/Model/HasOnlyReadOnly.cs | 14 +- .../Model/HealthCheckResult.cs | 10 +- .../Model/InlineResponseDefault.cs | 10 +- .../Model/IsoscelesTriangle.cs | 10 +- .../src/Org.OpenAPITools/Model/List.cs | 10 +- .../src/Org.OpenAPITools/Model/MapTest.cs | 20 +- ...dPropertiesAndAdditionalPropertiesClass.cs | 18 +- .../Model/Model200Response.cs | 12 +- .../src/Org.OpenAPITools/Model/ModelClient.cs | 10 +- .../src/Org.OpenAPITools/Model/Name.cs | 16 +- .../Org.OpenAPITools/Model/NullableClass.cs | 50 +- .../src/Org.OpenAPITools/Model/NumberOnly.cs | 8 +- .../Model/ObjectWithDeprecatedFields.cs | 20 +- .../src/Org.OpenAPITools/Model/Order.cs | 20 +- .../Org.OpenAPITools/Model/OuterComposite.cs | 14 +- .../src/Org.OpenAPITools/Model/ParentPet.cs | 11 +- .../src/Org.OpenAPITools/Model/Pet.cs | 26 +- .../Model/QuadrilateralInterface.cs | 10 +- .../Org.OpenAPITools/Model/ReadOnlyFirst.cs | 14 +- .../src/Org.OpenAPITools/Model/Return.cs | 8 +- .../Org.OpenAPITools/Model/ScaleneTriangle.cs | 14 +- .../Org.OpenAPITools/Model/ShapeInterface.cs | 10 +- .../Model/SimpleQuadrilateral.cs | 14 +- .../Model/SpecialModelName.cs | 12 +- .../src/Org.OpenAPITools/Model/Tag.cs | 12 +- .../Model/TriangleInterface.cs | 10 +- .../src/Org.OpenAPITools/Model/User.cs | 50 +- .../src/Org.OpenAPITools/Model/Whale.cs | 14 +- .../src/Org.OpenAPITools/Model/Zebra.cs | 12 +- .../Org.OpenAPITools/Api/AnotherFakeApi.cs | 37 +- .../src/Org.OpenAPITools/Api/DefaultApi.cs | 33 +- .../src/Org.OpenAPITools/Api/FakeApi.cs | 551 +++++++++++++----- .../Api/FakeClassnameTags123Api.cs | 37 +- .../src/Org.OpenAPITools/Api/PetApi.cs | 317 +++++++--- .../src/Org.OpenAPITools/Api/StoreApi.cs | 140 +++-- .../src/Org.OpenAPITools/Api/UserApi.cs | 300 +++++++--- .../Model/AdditionalPropertiesClass.cs | 34 +- .../src/Org.OpenAPITools/Model/Animal.cs | 10 +- .../src/Org.OpenAPITools/Model/ApiResponse.cs | 12 +- .../src/Org.OpenAPITools/Model/Apple.cs | 10 +- .../src/Org.OpenAPITools/Model/AppleReq.cs | 8 +- .../Model/ArrayOfArrayOfNumberOnly.cs | 6 +- .../Model/ArrayOfNumberOnly.cs | 6 +- .../src/Org.OpenAPITools/Model/ArrayTest.cs | 14 +- .../src/Org.OpenAPITools/Model/Banana.cs | 4 +- .../src/Org.OpenAPITools/Model/BananaReq.cs | 6 +- .../src/Org.OpenAPITools/Model/BasquePig.cs | 6 +- .../Org.OpenAPITools/Model/Capitalization.cs | 26 +- .../src/Org.OpenAPITools/Model/Cat.cs | 9 +- .../src/Org.OpenAPITools/Model/CatAllOf.cs | 4 +- .../src/Org.OpenAPITools/Model/Category.cs | 8 +- .../src/Org.OpenAPITools/Model/ChildCat.cs | 13 +- .../Org.OpenAPITools/Model/ChildCatAllOf.cs | 8 +- .../src/Org.OpenAPITools/Model/ClassModel.cs | 6 +- .../Model/ComplexQuadrilateral.cs | 10 +- .../src/Org.OpenAPITools/Model/DanishPig.cs | 6 +- .../Model/DeprecatedObject.cs | 6 +- .../src/Org.OpenAPITools/Model/Dog.cs | 11 +- .../src/Org.OpenAPITools/Model/DogAllOf.cs | 6 +- .../src/Org.OpenAPITools/Model/Drawing.cs | 18 +- .../src/Org.OpenAPITools/Model/EnumArrays.cs | 6 +- .../src/Org.OpenAPITools/Model/EnumTest.cs | 20 +- .../Model/EquilateralTriangle.cs | 10 +- .../src/Org.OpenAPITools/Model/File.cs | 6 +- .../Model/FileSchemaTestClass.cs | 10 +- .../src/Org.OpenAPITools/Model/Foo.cs | 6 +- .../src/Org.OpenAPITools/Model/FormatTest.cs | 76 ++- .../Model/GrandparentAnimal.cs | 6 +- .../Org.OpenAPITools/Model/HasOnlyReadOnly.cs | 10 +- .../Model/HealthCheckResult.cs | 6 +- .../Model/InlineResponseDefault.cs | 6 +- .../Model/IsoscelesTriangle.cs | 10 +- .../src/Org.OpenAPITools/Model/List.cs | 6 +- .../src/Org.OpenAPITools/Model/MapTest.cs | 16 +- ...dPropertiesAndAdditionalPropertiesClass.cs | 14 +- .../Model/Model200Response.cs | 8 +- .../src/Org.OpenAPITools/Model/ModelClient.cs | 6 +- .../src/Org.OpenAPITools/Model/Name.cs | 12 +- .../Org.OpenAPITools/Model/NullableClass.cs | 50 +- .../src/Org.OpenAPITools/Model/NumberOnly.cs | 4 +- .../Model/ObjectWithDeprecatedFields.cs | 16 +- .../src/Org.OpenAPITools/Model/Order.cs | 16 +- .../Org.OpenAPITools/Model/OuterComposite.cs | 10 +- .../src/Org.OpenAPITools/Model/ParentPet.cs | 7 +- .../src/Org.OpenAPITools/Model/Pet.cs | 22 +- .../Model/QuadrilateralInterface.cs | 6 +- .../Org.OpenAPITools/Model/ReadOnlyFirst.cs | 10 +- .../src/Org.OpenAPITools/Model/Return.cs | 4 +- .../Org.OpenAPITools/Model/ScaleneTriangle.cs | 10 +- .../Org.OpenAPITools/Model/ShapeInterface.cs | 6 +- .../Model/SimpleQuadrilateral.cs | 10 +- .../Model/SpecialModelName.cs | 8 +- .../src/Org.OpenAPITools/Model/Tag.cs | 8 +- .../Model/TriangleInterface.cs | 6 +- .../src/Org.OpenAPITools/Model/User.cs | 46 +- .../src/Org.OpenAPITools/Model/Whale.cs | 10 +- .../src/Org.OpenAPITools/Model/Zebra.cs | 12 +- .../src/Org.OpenAPITools/Api/PetApi.cs | 280 ++++++--- .../src/Org.OpenAPITools/Api/StoreApi.cs | 140 +++-- .../src/Org.OpenAPITools/Api/UserApi.cs | 300 +++++++--- .../src/Org.OpenAPITools/Model/ApiResponse.cs | 12 +- .../src/Org.OpenAPITools/Model/Category.cs | 8 +- .../src/Org.OpenAPITools/Model/Order.cs | 16 +- .../src/Org.OpenAPITools/Model/Pet.cs | 22 +- .../src/Org.OpenAPITools/Model/Tag.cs | 8 +- .../src/Org.OpenAPITools/Model/User.cs | 30 +- 417 files changed, 9873 insertions(+), 3788 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache index 86ea63f978e..ce2000f63e9 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/api.mustache @@ -259,7 +259,9 @@ namespace {{packageName}}.{{apiPackage}} {{^vendorExtensions.x-csharp-value-type}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) + { throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + } {{/vendorExtensions.x-csharp-value-type}} {{/required}} @@ -280,10 +282,16 @@ namespace {{packageName}}.{{apiPackage}} }; var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } {{#pathParams}} {{#required}} @@ -314,12 +322,12 @@ namespace {{packageName}}.{{apiPackage}} if ({{paramName}} != null) { {{#isDeepObject}} - {{#items.vars}} + {{#items.vars}} if ({{paramName}}.{{name}} != null) { localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); } - {{/items.vars}} + {{/items.vars}} {{^items}} localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); {{/items}} @@ -345,7 +353,8 @@ namespace {{packageName}}.{{apiPackage}} {{#required}} {{#isFile}} {{#isArray}} - foreach (var file in {{paramName}}) { + foreach (var file in {{paramName}}) + { localVarRequestOptions.FileParameters.Add("{{baseName}}", file); } {{/isArray}} @@ -362,7 +371,8 @@ namespace {{packageName}}.{{apiPackage}} { {{#isFile}} {{#isArray}} - foreach (var file in {{paramName}}) { + foreach (var file in {{paramName}}) + { localVarRequestOptions.FileParameters.Add("{{baseName}}", file); } {{/isArray}} @@ -445,11 +455,13 @@ namespace {{packageName}}.{{apiPackage}} // make the HTTP request var localVarResponse = this.Client.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}<{{{returnType}}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -493,7 +505,9 @@ namespace {{packageName}}.{{apiPackage}} {{^vendorExtensions.x-csharp-value-type}} // verify the required parameter '{{paramName}}' is set if ({{paramName}} == null) + { throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + } {{/vendorExtensions.x-csharp-value-type}} {{/required}} @@ -514,12 +528,17 @@ namespace {{packageName}}.{{apiPackage}} {{/produces}} }; - var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } {{#pathParams}} {{#required}} @@ -558,7 +577,8 @@ namespace {{packageName}}.{{apiPackage}} {{#required}} {{#isFile}} {{#isArray}} - foreach (var file in {{paramName}}) { + foreach (var file in {{paramName}}) + { localVarRequestOptions.FileParameters.Add("{{baseName}}", file); } {{/isArray}} @@ -575,7 +595,8 @@ namespace {{packageName}}.{{apiPackage}} { {{#isFile}} {{#isArray}} - foreach (var file in {{paramName}}) { + foreach (var file in {{paramName}}) + { localVarRequestOptions.FileParameters.Add("{{baseName}}", file); } {{/isArray}} @@ -659,13 +680,15 @@ namespace {{packageName}}.{{apiPackage}} {{/authMethods}} // make the HTTP request - var localVarResponse = await this.AsynchronousClient.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}Async<{{{returnType}}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache index e7dfa174d9b..3e554c1f980 100644 --- a/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-netcore/modelGeneric.mustache @@ -284,7 +284,7 @@ /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class {{classname}} {\n"); {{#parent}} sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); @@ -335,8 +335,9 @@ {{/useCompareNetObjects}} {{^useCompareNetObjects}} if (input == null) + { return false; - + } return {{#vars}}{{#parent}}base.Equals(input) && {{/parent}}{{^isContainer}} ( this.{{name}} == input.{{name}} || @@ -377,15 +378,19 @@ {{#vars}} {{^vendorExtensions.x-is-value-type}} if (this.{{name}} != null) - hashCode = hashCode * 59 + this.{{name}}.GetHashCode(); + { + hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); + } {{/vendorExtensions.x-is-value-type}} {{#vendorExtensions.x-is-value-type}} - hashCode = hashCode * 59 + this.{{name}}.GetHashCode(); + hashCode = (hashCode * 59) + this.{{name}}.GetHashCode(); {{/vendorExtensions.x-is-value-type}} {{/vars}} {{#isAdditionalPropertiesTrue}} if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } {{/isAdditionalPropertiesTrue}} return hashCode; } @@ -423,7 +428,10 @@ {{#parent}} {{^isArray}} {{^isMap}} - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } {{/isMap}} {{/isArray}} {{/parent}} @@ -432,7 +440,7 @@ {{^isEnum}} {{#maxLength}} // {{{name}}} ({{{dataType}}}) maxLength - if(this.{{{name}}} != null && this.{{{name}}}.Length > {{maxLength}}) + if (this.{{{name}}} != null && this.{{{name}}}.Length > {{maxLength}}) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be less than {{maxLength}}.", new [] { "{{{name}}}" }); } @@ -440,7 +448,7 @@ {{/maxLength}} {{#minLength}} // {{{name}}} ({{{dataType}}}) minLength - if(this.{{{name}}} != null && this.{{{name}}}.Length < {{minLength}}) + if (this.{{{name}}} != null && this.{{{name}}}.Length < {{minLength}}) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be greater than {{minLength}}.", new [] { "{{{name}}}" }); } @@ -448,7 +456,7 @@ {{/minLength}} {{#maximum}} // {{{name}}} ({{{dataType}}}) maximum - if(this.{{{name}}} > ({{{dataType}}}){{maximum}}) + if (this.{{{name}}} > ({{{dataType}}}){{maximum}}) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must be a value less than or equal to {{maximum}}.", new [] { "{{{name}}}" }); } @@ -456,7 +464,7 @@ {{/maximum}} {{#minimum}} // {{{name}}} ({{{dataType}}}) minimum - if(this.{{{name}}} < ({{{dataType}}}){{minimum}}) + if (this.{{{name}}} < ({{{dataType}}}){{minimum}}) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must be a value greater than or equal to {{minimum}}.", new [] { "{{{name}}}" }); } diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs index 30aaf723ab4..aa92ab8297b 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Api/MultipartApi.cs @@ -321,14 +321,21 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (files != null) { - foreach (var file in files) { + foreach (var file in files) + { localVarRequestOptions.FileParameters.Add("files", file); } } @@ -336,11 +343,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/multipart-array", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("MultipartArray", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -378,29 +387,37 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (files != null) { - foreach (var file in files) { + foreach (var file in files) + { localVarRequestOptions.FileParameters.Add("files", file); } } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/multipart-array", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("MultipartArray", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -429,7 +446,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'file' is set if (file == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'file' when calling MultipartApi->MultipartMixed"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -442,10 +461,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (marker != null) { @@ -456,11 +481,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/multipart-mixed", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("MultipartMixed", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -491,7 +518,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'file' is set if (file == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'file' when calling MultipartApi->MultipartMixed"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -504,12 +533,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (marker != null) { @@ -519,13 +553,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/multipart-mixed", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("MultipartMixed", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -561,10 +597,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (file != null) { @@ -574,11 +616,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/multipart-single", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("MultipartSingle", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -616,12 +660,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (file != null) { @@ -630,13 +679,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/multipart-single", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("MultipartSingle", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject.cs index 1fd426b347f..ae2d365c5e2 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class InlineObject {\n"); sb.Append(" Files: ").Append(Files).Append("\n"); sb.Append("}\n"); @@ -100,7 +100,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Files != null) - hashCode = hashCode * 59 + this.Files.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Files.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject1.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject1.cs index cda1fbd4a74..aee5f5ed83c 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject1.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject1.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class InlineObject1 {\n"); sb.Append(" File: ").Append(File).Append("\n"); sb.Append("}\n"); @@ -100,7 +100,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); + { + hashCode = (hashCode * 59) + this.File.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject2.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject2.cs index 18d60e31ac8..f16962cc4eb 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject2.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/InlineObject2.cs @@ -71,7 +71,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class InlineObject2 {\n"); sb.Append(" Marker: ").Append(Marker).Append("\n"); sb.Append(" File: ").Append(File).Append("\n"); @@ -118,9 +118,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Marker != null) - hashCode = hashCode * 59 + this.Marker.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Marker.GetHashCode(); + } if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); + { + hashCode = (hashCode * 59) + this.File.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedMarker.cs b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedMarker.cs index b10b4a7afeb..ee18f1fc14b 100644 --- a/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedMarker.cs +++ b/samples/client/others/csharp-netcore-complex-files/src/Org.OpenAPITools/Model/MultipartMixedMarker.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MultipartMixedMarker {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index ad48306e00c..ac8fbdcdc94 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,21 +237,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/another-fake/dummy", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -279,7 +289,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -293,24 +305,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/another-fake/dummy", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs index 8844aca4ab7..a9e5cfb9c4d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -221,20 +221,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/foo", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -271,23 +279,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/foo", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs index dab406002f8..57a99469634 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs @@ -945,20 +945,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/fake/health", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -995,23 +1003,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/health", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1049,21 +1064,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/boolean", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1103,24 +1126,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/boolean", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1158,21 +1188,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/composite", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1212,24 +1250,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/composite", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1267,21 +1312,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/number", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1321,24 +1374,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/number", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1376,21 +1436,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/string", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1430,24 +1498,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/string", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1482,20 +1557,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get>("/fake/array-of-enums", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1532,23 +1615,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/fake/array-of-enums", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1575,7 +1665,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1588,21 +1680,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1631,7 +1731,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1644,24 +1746,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1690,11 +1799,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1707,10 +1820,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; @@ -1718,11 +1837,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-query-params", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1753,11 +1874,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1770,25 +1895,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-query-params", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1816,7 +1948,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1830,21 +1964,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1874,7 +2016,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1888,24 +2032,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1958,11 +2109,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1975,10 +2130,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2034,11 +2195,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2093,11 +2256,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2110,12 +2277,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2170,13 +2342,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2226,10 +2400,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2267,11 +2447,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2323,12 +2505,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2365,13 +2552,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2416,10 +2605,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2446,11 +2641,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2497,12 +2694,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2528,13 +2730,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2561,7 +2765,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2574,21 +2780,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request var localVarResponse = this.Client.Post("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2617,7 +2831,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2630,24 +2846,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2676,11 +2899,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2693,10 +2920,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter @@ -2704,11 +2937,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake/jsonFormData", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2739,11 +2974,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2756,25 +2995,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/jsonFormData", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2809,23 +3055,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2837,10 +3093,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2851,11 +3113,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/test-query-parameters", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2892,23 +3156,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2920,12 +3194,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2935,13 +3214,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/test-query-parameters", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index d4fbb5868ad..c2852b36a44 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,10 +237,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -250,11 +258,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Patch("/fake_classname_test", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -284,7 +294,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -298,12 +310,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -314,13 +331,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake_classname_test", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs index d73282dfca5..39d2e425e63 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs @@ -586,7 +586,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -600,10 +602,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -632,11 +640,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -665,7 +675,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -679,12 +691,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -712,13 +729,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -755,10 +774,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -775,11 +800,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -818,12 +845,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -839,13 +871,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -873,7 +907,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -887,10 +923,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -919,11 +961,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByStatus", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -953,7 +997,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -967,12 +1013,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -1000,13 +1051,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1036,7 +1089,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1050,10 +1105,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1082,11 +1143,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByTags", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1118,7 +1181,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1132,12 +1197,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1165,13 +1235,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1209,10 +1281,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1224,11 +1302,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1268,12 +1348,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1284,13 +1369,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1317,7 +1404,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1420,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1363,11 +1458,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1396,7 +1493,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1410,12 +1509,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1443,13 +1547,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1489,10 +1595,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1513,11 +1625,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1559,12 +1673,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1584,13 +1703,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1632,10 +1753,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1656,11 +1783,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1704,12 +1833,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1729,13 +1863,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1767,7 +1903,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1781,10 +1919,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1802,11 +1946,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1840,7 +1986,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1854,12 +2002,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1876,13 +2029,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs index ad7387db705..7cda385b3b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/StoreApi.cs @@ -345,7 +345,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -357,21 +359,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -400,7 +410,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -412,24 +424,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -464,10 +483,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -478,11 +503,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/store/inventory", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -519,12 +546,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -534,13 +566,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/store/inventory", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -578,21 +612,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -632,24 +674,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -677,7 +726,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -692,21 +743,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request var localVarResponse = this.Client.Post("/store/order", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -736,7 +795,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -751,24 +812,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/store/order", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs index a2f2598c8ac..a1716303f6f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/UserApi.cs @@ -517,7 +517,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -530,21 +532,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -573,7 +583,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -586,24 +598,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -630,7 +649,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -643,21 +664,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithArray", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -686,7 +715,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -699,24 +730,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithArray", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -743,7 +781,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -756,21 +796,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithList", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -799,7 +847,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -812,24 +862,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithList", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -856,7 +913,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -868,21 +927,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -911,7 +978,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -923,24 +992,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -968,7 +1044,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -982,21 +1060,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1026,7 +1112,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1040,24 +1128,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1087,11 +1182,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1105,10 +1204,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); @@ -1116,11 +1221,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/user/login", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1152,11 +1259,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1170,25 +1281,32 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/login", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1221,20 +1339,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/user/logout", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1269,23 +1395,30 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/logout", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1314,11 +1447,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1468,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; @@ -1342,11 +1485,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1377,11 +1522,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1394,25 +1543,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 33b03936674..ec5eb3cdd93 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -261,7 +261,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); @@ -315,23 +315,41 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapProperty != null) - hashCode = hashCode * 59 + this.MapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); + } if (this.MapOfMapProperty != null) - hashCode = hashCode * 59 + this.MapOfMapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); + } if (this.Anytype1 != null) - hashCode = hashCode * 59 + this.Anytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype1 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype2 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype3 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + } if (this.EmptyMap != null) - hashCode = hashCode * 59 + this.EmptyMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesString != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs index b741cb66392..1ecea975be7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Animal.cs @@ -119,7 +119,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Animal {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Color: ").Append(Color).Append("\n"); @@ -167,11 +167,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.Color != null) - hashCode = hashCode * 59 + this.Color.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Color.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ApiResponse.cs index acceaf62ed8..87db69a8d85 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -130,7 +130,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -178,13 +178,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Code.GetHashCode(); + hashCode = (hashCode * 59) + this.Code.GetHashCode(); if (this.Type != null) - hashCode = hashCode * 59 + this.Type.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } if (this.Message != null) - hashCode = hashCode * 59 + this.Message.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Message.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Apple.cs index 66244fcd4b2..f5bfb1230b5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Apple.cs @@ -104,7 +104,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Apple {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Origin: ").Append(Origin).Append("\n"); @@ -152,11 +152,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } if (this.Origin != null) - hashCode = hashCode * 59 + this.Origin.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Origin.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs index 5a4400200a2..5f042a01cf9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/AppleReq.cs @@ -106,7 +106,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AppleReq {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Mealy: ").Append(Mealy).Append("\n"); @@ -153,8 +153,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); - hashCode = hashCode * 59 + this.Mealy.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index dfcbdff093b..aadaaa72020 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfArrayOfNumberOnly {\n"); sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -125,9 +125,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 0ea09adcd6d..66f7bcce0ac 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfNumberOnly {\n"); sb.Append(" ArrayNumber: ").Append(ArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -125,9 +125,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayTest.cs index 70c54edeeea..1825d97b3ea 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -130,7 +130,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayTest {\n"); sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); @@ -179,13 +179,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayOfString != null) - hashCode = hashCode * 59 + this.ArrayOfString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); + } if (this.ArrayArrayOfInteger != null) - hashCode = hashCode * 59 + this.ArrayArrayOfInteger.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); + } if (this.ArrayArrayOfModel != null) - hashCode = hashCode * 59 + this.ArrayArrayOfModel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Banana.cs index 46b952e9a18..3bdc2706327 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Banana.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Banana {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -124,9 +124,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs index adfa4cb5164..e7289cd6f3e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BananaReq.cs @@ -102,7 +102,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BananaReq {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" Sweet: ").Append(Sweet).Append("\n"); @@ -148,8 +148,8 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); - hashCode = hashCode * 59 + this.Sweet.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs index c745514a4ee..0ba9ff1eedf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/BasquePig.cs @@ -90,7 +90,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BasquePig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -137,9 +137,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Capitalization.cs index 428a0ad6672..1cee58da84b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Capitalization.cs @@ -209,7 +209,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Capitalization {\n"); sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); @@ -261,19 +261,33 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SmallCamel != null) - hashCode = hashCode * 59 + this.SmallCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); + } if (this.CapitalCamel != null) - hashCode = hashCode * 59 + this.CapitalCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); + } if (this.SmallSnake != null) - hashCode = hashCode * 59 + this.SmallSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); + } if (this.CapitalSnake != null) - hashCode = hashCode * 59 + this.CapitalSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); + } if (this.SCAETHFlowPoints != null) - hashCode = hashCode * 59 + this.SCAETHFlowPoints.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); + } if (this.ATT_NAME != null) - hashCode = hashCode * 59 + this.ATT_NAME.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs index acc5f870fcd..a07eac2b8ee 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Cat.cs @@ -90,7 +90,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Cat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); @@ -137,9 +137,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -161,7 +163,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/CatAllOf.cs index 113357ddf91..e31e45a795f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class CatAllOf {\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -124,9 +124,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs index 7bb04693da0..621dff0ce0a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Category.cs @@ -116,7 +116,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -163,11 +163,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs index 495e9d6c568..bdef892ab86 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs @@ -130,7 +130,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -179,10 +179,14 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -204,7 +208,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index 61ca1419437..7c39109418e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -119,7 +119,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCatAllOf {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); @@ -167,10 +167,14 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ClassModel.cs index 72483a012c6..f223ab882b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ClassModel.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ClassModel {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -125,9 +125,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 9d1d32cd9db..7288bffb395 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ComplexQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -168,11 +168,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs index 7adee34852a..1955404a458 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DanishPig.cs @@ -90,7 +90,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DanishPig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -137,9 +137,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DeprecatedObject.cs index 4ef628eca2b..b2aeb211163 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DeprecatedObject {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -125,9 +125,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs index e876d8dc964..b3709a99dd9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Dog.cs @@ -90,7 +90,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Dog {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); @@ -138,9 +138,13 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -162,7 +166,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DogAllOf.cs index 84518fadc2c..40e42a0bf82 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DogAllOf {\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -125,9 +125,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs index 5e47d778777..a7ab7daa3b2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs @@ -149,7 +149,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); @@ -199,13 +199,21 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.MainShape != null) - hashCode = hashCode * 59 + this.MainShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); + } if (this.ShapeOrNull != null) - hashCode = hashCode * 59 + this.ShapeOrNull.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); + } if (this.NullableShape != null) - hashCode = hashCode * 59 + this.NullableShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); + } if (this.Shapes != null) - hashCode = hashCode * 59 + this.Shapes.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs index 304ec4c234c..d4cc2bbcf31 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -149,7 +149,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumArrays {\n"); sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); sb.Append(" ArrayEnum: ").Append(ArrayEnum).Append("\n"); @@ -196,10 +196,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustSymbol.GetHashCode(); - hashCode = hashCode * 59 + this.ArrayEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs index 914428919ac..605274f7c1c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EnumTest.cs @@ -418,7 +418,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); @@ -472,17 +472,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.EnumString.GetHashCode(); - hashCode = hashCode * 59 + this.EnumStringRequired.GetHashCode(); - hashCode = hashCode * 59 + this.EnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.EnumIntegerOnly.GetHashCode(); - hashCode = hashCode * 59 + this.EnumNumber.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnum.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumDefaultValue.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumIntegerDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumStringRequired.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 21fe08e7436..3029945d8a3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EquilateralTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -168,11 +168,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/File.cs index 4316936a2b1..521cf9bf4d4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/File.cs @@ -79,7 +79,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class File {\n"); sb.Append(" SourceURI: ").Append(SourceURI).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -126,9 +126,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SourceURI != null) - hashCode = hashCode * 59 + this.SourceURI.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index c6759aa2490..841cb56f649 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -104,7 +104,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FileSchemaTestClass {\n"); sb.Append(" File: ").Append(File).Append("\n"); sb.Append(" Files: ").Append(Files).Append("\n"); @@ -152,11 +152,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); + { + hashCode = (hashCode * 59) + this.File.GetHashCode(); + } if (this.Files != null) - hashCode = hashCode * 59 + this.Files.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Files.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Foo.cs index 1e78c6575e0..dcbf1143534 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Foo.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Foo {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -124,9 +124,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs index 80c359e71b4..ef25bf8889d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/FormatTest.cs @@ -487,7 +487,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); @@ -548,33 +548,53 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Integer.GetHashCode(); - hashCode = hashCode * 59 + this.Int32.GetHashCode(); - hashCode = hashCode * 59 + this.Int64.GetHashCode(); - hashCode = hashCode * 59 + this.Number.GetHashCode(); - hashCode = hashCode * 59 + this.Float.GetHashCode(); - hashCode = hashCode * 59 + this.Double.GetHashCode(); - hashCode = hashCode * 59 + this.Decimal.GetHashCode(); + hashCode = (hashCode * 59) + this.Integer.GetHashCode(); + hashCode = (hashCode * 59) + this.Int32.GetHashCode(); + hashCode = (hashCode * 59) + this.Int64.GetHashCode(); + hashCode = (hashCode * 59) + this.Number.GetHashCode(); + hashCode = (hashCode * 59) + this.Float.GetHashCode(); + hashCode = (hashCode * 59) + this.Double.GetHashCode(); + hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.Byte != null) - hashCode = hashCode * 59 + this.Byte.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Byte.GetHashCode(); + } if (this.Binary != null) - hashCode = hashCode * 59 + this.Binary.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Binary.GetHashCode(); + } if (this.Date != null) - hashCode = hashCode * 59 + this.Date.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Date.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.PatternWithDigits != null) - hashCode = hashCode * 59 + this.PatternWithDigits.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); + } if (this.PatternWithDigitsAndDelimiter != null) - hashCode = hashCode * 59 + this.PatternWithDigitsAndDelimiter.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -587,61 +607,61 @@ namespace Org.OpenAPITools.Model public IEnumerable Validate(ValidationContext validationContext) { // Integer (int) maximum - if(this.Integer > (int)100) + if (this.Integer > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if(this.Integer < (int)10) + if (this.Integer < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } // Int32 (int) maximum - if(this.Int32 > (int)200) + if (this.Int32 > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if(this.Int32 < (int)20) + if (this.Int32 < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Number (decimal) maximum - if(this.Number > (decimal)543.2) + if (this.Number > (decimal)543.2) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); } // Number (decimal) minimum - if(this.Number < (decimal)32.1) + if (this.Number < (decimal)32.1) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); } // Float (float) maximum - if(this.Float > (float)987.6) + if (this.Float > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); } // Float (float) minimum - if(this.Float < (float)54.3) + if (this.Float < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); } // Double (double) maximum - if(this.Double > (double)123.4) + if (this.Double > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); } // Double (double) minimum - if(this.Double < (double)67.8) + if (this.Double < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); } @@ -654,13 +674,13 @@ namespace Org.OpenAPITools.Model } // Password (string) maxLength - if(this.Password != null && this.Password.Length > 64) + if (this.Password != null && this.Password.Length > 64) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); } // Password (string) minLength - if(this.Password != null && this.Password.Length < 10) + if (this.Password != null && this.Password.Length < 10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 6ca684a89b1..f26d700c207 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -94,7 +94,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class GrandparentAnimal {\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -141,9 +141,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.PetType != null) - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index f6219182b29..52099a7095e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -81,7 +81,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HasOnlyReadOnly {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Foo: ").Append(Foo).Append("\n"); @@ -129,11 +129,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Foo != null) - hashCode = hashCode * 59 + this.Foo.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Foo.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HealthCheckResult.cs index 80aa2e7327e..aa33b076d06 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HealthCheckResult {\n"); sb.Append(" NullableMessage: ").Append(NullableMessage).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -125,9 +125,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.NullableMessage != null) - hashCode = hashCode * 59 + this.NullableMessage.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs index 23083ccef40..909c34c2cef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/InlineResponseDefault.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponseDefault {\n"); sb.Append(" String: ").Append(String).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -125,9 +125,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 6fa6aec800f..ca9a10e5f9e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -110,7 +110,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class IsoscelesTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -157,9 +157,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/List.cs index 7b26a68a173..a55d149d4af 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/List.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class List {\n"); sb.Append(" _123List: ").Append(_123List).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -125,9 +125,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._123List != null) - hashCode = hashCode * 59 + this._123List.GetHashCode(); + { + hashCode = (hashCode * 59) + this._123List.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs index 80b9989b72c..fa45d1411a3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MapTest.cs @@ -179,7 +179,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MapTest {\n"); sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); @@ -229,14 +229,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapMapOfString != null) - hashCode = hashCode * 59 + this.MapMapOfString.GetHashCode(); - hashCode = hashCode * 59 + this.MapOfEnumString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); if (this.DirectMap != null) - hashCode = hashCode * 59 + this.DirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); + } if (this.IndirectMap != null) - hashCode = hashCode * 59 + this.IndirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 920ac973715..7eabc6242c8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -130,7 +130,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); @@ -179,13 +179,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Map != null) - hashCode = hashCode * 59 + this.Map.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Map.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Model200Response.cs index 4d75dd7b30a..c1c8a389063 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Model200Response.cs @@ -104,7 +104,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Model200Response {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); @@ -151,11 +151,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = (hashCode * 59) + this.Name.GetHashCode(); if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ModelClient.cs index e7f52aeba3c..d9a2d7b846c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ModelClient.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ModelClient {\n"); sb.Append(" _Client: ").Append(_Client).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -125,9 +125,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._Client != null) - hashCode = hashCode * 59 + this._Client.GetHashCode(); + { + hashCode = (hashCode * 59) + this._Client.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs index a613b9d82a9..dd8a2a2aed9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Name.cs @@ -140,7 +140,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" _Name: ").Append(_Name).Append("\n"); sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); @@ -189,13 +189,17 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Name.GetHashCode(); - hashCode = hashCode * 59 + this.SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + this._Name.GetHashCode(); + hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); if (this.Property != null) - hashCode = hashCode * 59 + this.Property.GetHashCode(); - hashCode = hashCode * 59 + this._123Number.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Property.GetHashCode(); + } + hashCode = (hashCode * 59) + this._123Number.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs index 31135c0c65d..428f7c3deef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs @@ -358,7 +358,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); @@ -416,29 +416,53 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.IntegerProp != null) - hashCode = hashCode * 59 + this.IntegerProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); + } if (this.NumberProp != null) - hashCode = hashCode * 59 + this.NumberProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); + } if (this.BooleanProp != null) - hashCode = hashCode * 59 + this.BooleanProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); + } if (this.StringProp != null) - hashCode = hashCode * 59 + this.StringProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); + } if (this.DateProp != null) - hashCode = hashCode * 59 + this.DateProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); + } if (this.DatetimeProp != null) - hashCode = hashCode * 59 + this.DatetimeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); + } if (this.ArrayNullableProp != null) - hashCode = hashCode * 59 + this.ArrayNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); + } if (this.ArrayAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ArrayAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); + } if (this.ArrayItemsNullable != null) - hashCode = hashCode * 59 + this.ArrayItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); + } if (this.ObjectNullableProp != null) - hashCode = hashCode * 59 + this.ObjectNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); + } if (this.ObjectAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ObjectAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); + } if (this.ObjectItemsNullable != null) - hashCode = hashCode * 59 + this.ObjectItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NumberOnly.cs index c2f0ec4d5ec..4e542535451 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NumberOnly {\n"); sb.Append(" JustNumber: ").Append(JustNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -124,9 +124,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.JustNumber.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 4362fdb9329..3d6d12d562b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -159,7 +159,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ObjectWithDeprecatedFields {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); @@ -209,14 +209,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); - hashCode = hashCode * 59 + this.Id.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.DeprecatedRef != null) - hashCode = hashCode * 59 + this.DeprecatedRef.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); + } if (this.Bars != null) - hashCode = hashCode * 59 + this.Bars.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bars.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Order.cs index 22b3dd19d6c..21fb784543b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Order.cs @@ -237,7 +237,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); @@ -288,15 +288,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); - hashCode = hashCode * 59 + this.PetId.GetHashCode(); - hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.PetId.GetHashCode(); + hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); if (this.ShipDate != null) - hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); - hashCode = hashCode * 59 + this.Complete.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + hashCode = (hashCode * 59) + this.Complete.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterComposite.cs index 634161d1bf5..8521e32d470 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -130,7 +130,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class OuterComposite {\n"); sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); sb.Append(" MyString: ").Append(MyString).Append("\n"); @@ -178,12 +178,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.MyNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.MyNumber.GetHashCode(); if (this.MyString != null) - hashCode = hashCode * 59 + this.MyString.GetHashCode(); - hashCode = hashCode * 59 + this.MyBoolean.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MyString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs index 899984fcc5b..ac986b555ef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ParentPet.cs @@ -64,7 +64,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ParentPet {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -111,7 +111,9 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -133,7 +135,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs index 39c8380ae87..4737a5b7aee 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Pet.cs @@ -254,7 +254,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Category: ").Append(Category).Append("\n"); @@ -305,18 +305,28 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Category != null) - hashCode = hashCode * 59 + this.Category.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Category.GetHashCode(); + } if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.PhotoUrls != null) - hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); + } if (this.Tags != null) - hashCode = hashCode * 59 + this.Tags.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Tags.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index 983dfc4be99..75fa6ad7271 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -90,7 +90,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class QuadrilateralInterface {\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -137,9 +137,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index fc5e685f9c9..4152b8eaa2d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -92,7 +92,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ReadOnlyFirst {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Baz: ").Append(Baz).Append("\n"); @@ -140,11 +140,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Baz != null) - hashCode = hashCode * 59 + this.Baz.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Baz.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Return.cs index b3c35543c15..b9681ebec3c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Return.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Return {\n"); sb.Append(" _Return: ").Append(_Return).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -124,9 +124,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Return.GetHashCode(); + hashCode = (hashCode * 59) + this._Return.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 7a98eae2dd4..a0c0e1da8b1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ScaleneTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -168,11 +168,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs index edd12424c1d..619a8098664 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -90,7 +90,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ShapeInterface {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -137,9 +137,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 94b69ee95ee..0c3d83f8e66 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -120,7 +120,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SimpleQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -168,11 +168,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SpecialModelName.cs index 6594fe5bf7e..647b87399fd 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -104,7 +104,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SpecialModelName {\n"); sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); sb.Append(" _SpecialModelName: ").Append(_SpecialModelName).Append("\n"); @@ -151,11 +151,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.SpecialPropertyName.GetHashCode(); + hashCode = (hashCode * 59) + this.SpecialPropertyName.GetHashCode(); if (this._SpecialModelName != null) - hashCode = hashCode * 59 + this._SpecialModelName.GetHashCode(); + { + hashCode = (hashCode * 59) + this._SpecialModelName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Tag.cs index b50f051e43b..93d34bef1a1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Tag.cs @@ -104,7 +104,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Tag {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -151,11 +151,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs index 78993edeee2..183b3be09fb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -90,7 +90,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class TriangleInterface {\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -137,9 +137,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/User.cs index 9d63f029833..9309128511c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/User.cs @@ -369,7 +369,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); @@ -426,30 +426,52 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Username != null) - hashCode = hashCode * 59 + this.Username.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Username.GetHashCode(); + } if (this.FirstName != null) - hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); + } if (this.LastName != null) - hashCode = hashCode * 59 + this.LastName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.LastName.GetHashCode(); + } if (this.Email != null) - hashCode = hashCode * 59 + this.Email.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Email.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.Phone != null) - hashCode = hashCode * 59 + this.Phone.GetHashCode(); - hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Phone.GetHashCode(); + } + hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); if (this.ObjectWithNoDeclaredProps != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredProps.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); + } if (this.ObjectWithNoDeclaredPropsNullable != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + } if (this.AnyTypeProp != null) - hashCode = hashCode * 59 + this.AnyTypeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); + } if (this.AnyTypePropNullable != null) - hashCode = hashCode * 59 + this.AnyTypePropNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs index 00a9182cc19..31f06658f01 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Whale.cs @@ -142,7 +142,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Whale {\n"); sb.Append(" HasBaleen: ").Append(HasBaleen).Append("\n"); sb.Append(" HasTeeth: ").Append(HasTeeth).Append("\n"); @@ -190,12 +190,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.HasBaleen.GetHashCode(); - hashCode = hashCode * 59 + this.HasTeeth.GetHashCode(); + hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); + hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs index bce8a5f35c7..f4bf84c8647 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs @@ -144,7 +144,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -192,11 +192,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Type.GetHashCode(); + hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 9fa7018dde7..fb0eca6557b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -118,7 +118,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); @@ -172,23 +172,41 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapProperty != null) - hashCode = hashCode * 59 + this.MapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); + } if (this.MapOfMapProperty != null) - hashCode = hashCode * 59 + this.MapOfMapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); + } if (this.Anytype1 != null) - hashCode = hashCode * 59 + this.Anytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype1 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype2 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype3 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + } if (this.EmptyMap != null) - hashCode = hashCode * 59 + this.EmptyMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesString != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs index 743dedc1acd..4363ebe1138 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Animal.cs @@ -86,7 +86,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Animal {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Color: ").Append(Color).Append("\n"); @@ -134,11 +134,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.Color != null) - hashCode = hashCode * 59 + this.Color.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Color.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs index 53bf2456b0c..0bf23edced7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -125,13 +125,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Code.GetHashCode(); + hashCode = (hashCode * 59) + this.Code.GetHashCode(); if (this.Type != null) - hashCode = hashCode * 59 + this.Type.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } if (this.Message != null) - hashCode = hashCode * 59 + this.Message.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Message.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs index 1e4f098f6e8..26fb7d71d1c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Apple.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Apple {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Origin: ").Append(Origin).Append("\n"); @@ -117,11 +117,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } if (this.Origin != null) - hashCode = hashCode * 59 + this.Origin.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Origin.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs index beaf04983f9..33fca86a411 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/AppleReq.cs @@ -71,7 +71,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AppleReq {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Mealy: ").Append(Mealy).Append("\n"); @@ -118,8 +118,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); - hashCode = hashCode * 59 + this.Mealy.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index ff179798aec..3de85f7f649 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfArrayOfNumberOnly {\n"); sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index ec3092c1a7c..8fad145c570 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfNumberOnly {\n"); sb.Append(" ArrayNumber: ").Append(ArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs index 37d45ae2dda..7c9c235507a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayTest {\n"); sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); @@ -126,13 +126,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayOfString != null) - hashCode = hashCode * 59 + this.ArrayOfString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); + } if (this.ArrayArrayOfInteger != null) - hashCode = hashCode * 59 + this.ArrayArrayOfInteger.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); + } if (this.ArrayArrayOfModel != null) - hashCode = hashCode * 59 + this.ArrayArrayOfModel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs index 81074ebe6ea..8b340fae031 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Banana.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Banana {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs index 01df9fc3288..0bb74117eec 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BananaReq.cs @@ -67,7 +67,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BananaReq {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" Sweet: ").Append(Sweet).Append("\n"); @@ -113,8 +113,8 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); - hashCode = hashCode * 59 + this.Sweet.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs index a72f3c5a21f..56ee53e80a8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/BasquePig.cs @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BasquePig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,9 +120,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs index 63ae477d671..463d63a939f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Capitalization.cs @@ -102,7 +102,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Capitalization {\n"); sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); @@ -154,19 +154,33 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SmallCamel != null) - hashCode = hashCode * 59 + this.SmallCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); + } if (this.CapitalCamel != null) - hashCode = hashCode * 59 + this.CapitalCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); + } if (this.SmallSnake != null) - hashCode = hashCode * 59 + this.SmallSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); + } if (this.CapitalSnake != null) - hashCode = hashCode * 59 + this.CapitalSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); + } if (this.SCAETHFlowPoints != null) - hashCode = hashCode * 59 + this.SCAETHFlowPoints.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); + } if (this.ATT_NAME != null) - hashCode = hashCode * 59 + this.ATT_NAME.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs index 84875a42d1b..a4913aebad7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Cat.cs @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Cat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); @@ -120,9 +120,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -144,7 +146,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs index 216ac7a7b02..d126477f736 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class CatAllOf {\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs index 67a5c3ee748..59a4fbad51b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Category.cs @@ -81,7 +81,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -128,11 +128,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs index 9031f601165..a6603b7cb85 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs @@ -93,7 +93,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -142,10 +142,14 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -167,7 +171,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index f7e9e82de3e..f2ae1bcb054 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -83,7 +83,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCatAllOf {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); @@ -131,10 +131,14 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs index 26ad94fcb39..66db9245d6b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ClassModel.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ClassModel {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 466fda94d01..98f8f19c014 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ComplexQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -133,11 +133,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs index ae07caed6f9..08cc2665dde 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DanishPig.cs @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DanishPig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,9 +120,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DeprecatedObject.cs index 804b8b4fafa..afd96916888 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DeprecatedObject {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs index e15631d3415..190866102de 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Dog.cs @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Dog {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -145,7 +149,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs index eacfb595623..7d6c49788a0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DogAllOf {\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs index b24289870b9..7610f5c3bc1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); @@ -128,13 +128,21 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.MainShape != null) - hashCode = hashCode * 59 + this.MainShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); + } if (this.ShapeOrNull != null) - hashCode = hashCode * 59 + this.ShapeOrNull.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); + } if (this.NullableShape != null) - hashCode = hashCode * 59 + this.NullableShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); + } if (this.Shapes != null) - hashCode = hashCode * 59 + this.Shapes.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs index 8bb69d7fd90..7e5d509dd8b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -110,7 +110,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumArrays {\n"); sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); sb.Append(" ArrayEnum: ").Append(ArrayEnum).Append("\n"); @@ -157,10 +157,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustSymbol.GetHashCode(); - hashCode = hashCode * 59 + this.ArrayEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs index 14ae48281f0..a5a0c32d3a3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EnumTest.cs @@ -239,7 +239,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); @@ -293,17 +293,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.EnumString.GetHashCode(); - hashCode = hashCode * 59 + this.EnumStringRequired.GetHashCode(); - hashCode = hashCode * 59 + this.EnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.EnumIntegerOnly.GetHashCode(); - hashCode = hashCode * 59 + this.EnumNumber.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnum.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumDefaultValue.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumIntegerDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumStringRequired.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 7b7ae970ad2..c76a4adf9c0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EquilateralTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -133,11 +133,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs index 55c558f7ccf..36418ba1676 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/File.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class File {\n"); sb.Append(" SourceURI: ").Append(SourceURI).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -109,9 +109,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SourceURI != null) - hashCode = hashCode * 59 + this.SourceURI.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index 0a0e64cae8a..13d9f45e3f2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FileSchemaTestClass {\n"); sb.Append(" File: ").Append(File).Append("\n"); sb.Append(" Files: ").Append(Files).Append("\n"); @@ -117,11 +117,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); + { + hashCode = (hashCode * 59) + this.File.GetHashCode(); + } if (this.Files != null) - hashCode = hashCode * 59 + this.Files.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Files.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs index 3db81e42d4c..c42991826b1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Foo.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Foo {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -109,9 +109,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs index cdb7b684a77..6b2fa36ee3d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/FormatTest.cs @@ -200,7 +200,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); @@ -261,33 +261,53 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Integer.GetHashCode(); - hashCode = hashCode * 59 + this.Int32.GetHashCode(); - hashCode = hashCode * 59 + this.Int64.GetHashCode(); - hashCode = hashCode * 59 + this.Number.GetHashCode(); - hashCode = hashCode * 59 + this.Float.GetHashCode(); - hashCode = hashCode * 59 + this.Double.GetHashCode(); - hashCode = hashCode * 59 + this.Decimal.GetHashCode(); + hashCode = (hashCode * 59) + this.Integer.GetHashCode(); + hashCode = (hashCode * 59) + this.Int32.GetHashCode(); + hashCode = (hashCode * 59) + this.Int64.GetHashCode(); + hashCode = (hashCode * 59) + this.Number.GetHashCode(); + hashCode = (hashCode * 59) + this.Float.GetHashCode(); + hashCode = (hashCode * 59) + this.Double.GetHashCode(); + hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.Byte != null) - hashCode = hashCode * 59 + this.Byte.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Byte.GetHashCode(); + } if (this.Binary != null) - hashCode = hashCode * 59 + this.Binary.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Binary.GetHashCode(); + } if (this.Date != null) - hashCode = hashCode * 59 + this.Date.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Date.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.PatternWithDigits != null) - hashCode = hashCode * 59 + this.PatternWithDigits.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); + } if (this.PatternWithDigitsAndDelimiter != null) - hashCode = hashCode * 59 + this.PatternWithDigitsAndDelimiter.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -300,61 +320,61 @@ namespace Org.OpenAPITools.Model public IEnumerable Validate(ValidationContext validationContext) { // Integer (int) maximum - if(this.Integer > (int)100) + if (this.Integer > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if(this.Integer < (int)10) + if (this.Integer < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } // Int32 (int) maximum - if(this.Int32 > (int)200) + if (this.Int32 > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if(this.Int32 < (int)20) + if (this.Int32 < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Number (decimal) maximum - if(this.Number > (decimal)543.2) + if (this.Number > (decimal)543.2) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); } // Number (decimal) minimum - if(this.Number < (decimal)32.1) + if (this.Number < (decimal)32.1) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); } // Float (float) maximum - if(this.Float > (float)987.6) + if (this.Float > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); } // Float (float) minimum - if(this.Float < (float)54.3) + if (this.Float < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); } // Double (double) maximum - if(this.Double > (double)123.4) + if (this.Double > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); } // Double (double) minimum - if(this.Double < (double)67.8) + if (this.Double < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); } @@ -367,13 +387,13 @@ namespace Org.OpenAPITools.Model } // Password (string) maxLength - if(this.Password != null && this.Password.Length > 64) + if (this.Password != null && this.Password.Length > 64) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); } // Password (string) minLength - if(this.Password != null && this.Password.Length < 10) + if (this.Password != null && this.Password.Length < 10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 269d213d3d0..7b1b41d58af 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class GrandparentAnimal {\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -124,9 +124,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.PetType != null) - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 37696997d07..18b30851956 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -82,7 +82,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HasOnlyReadOnly {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Foo: ").Append(Foo).Append("\n"); @@ -130,11 +130,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Foo != null) - hashCode = hashCode * 59 + this.Foo.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Foo.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs index 11fcc6f7e25..0764cab0edf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HealthCheckResult {\n"); sb.Append(" NullableMessage: ").Append(NullableMessage).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.NullableMessage != null) - hashCode = hashCode * 59 + this.NullableMessage.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs index 38d0ec6ca65..6e0c37e257a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponseDefault {\n"); sb.Append(" String: ").Append(String).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 30d639d57b6..2f93e58d26d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -75,7 +75,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class IsoscelesTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -122,9 +122,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs index dbbac7eb34c..9610ab8c272 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/List.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class List {\n"); sb.Append(" _123List: ").Append(_123List).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._123List != null) - hashCode = hashCode * 59 + this._123List.GetHashCode(); + { + hashCode = (hashCode * 59) + this._123List.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs index 9116d8998c7..9a7ca84088e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MapTest.cs @@ -106,7 +106,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MapTest {\n"); sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); @@ -156,14 +156,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapMapOfString != null) - hashCode = hashCode * 59 + this.MapMapOfString.GetHashCode(); - hashCode = hashCode * 59 + this.MapOfEnumString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); if (this.DirectMap != null) - hashCode = hashCode * 59 + this.DirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); + } if (this.IndirectMap != null) - hashCode = hashCode * 59 + this.IndirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index f1e770c39d3..22690e54091 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); @@ -126,13 +126,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Map != null) - hashCode = hashCode * 59 + this.Map.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Map.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs index 55cc5b17abd..1f636909766 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Model200Response.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Model200Response {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); @@ -116,11 +116,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = (hashCode * 59) + this.Name.GetHashCode(); if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs index d77e05d93a9..564fedf5ae4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ModelClient.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ModelClient {\n"); sb.Append(" _Client: ").Append(_Client).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._Client != null) - hashCode = hashCode * 59 + this._Client.GetHashCode(); + { + hashCode = (hashCode * 59) + this._Client.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs index 30c4db076e3..47c53759a05 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Name.cs @@ -105,7 +105,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" _Name: ").Append(_Name).Append("\n"); sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); @@ -154,13 +154,17 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Name.GetHashCode(); - hashCode = hashCode * 59 + this.SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + this._Name.GetHashCode(); + hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); if (this.Property != null) - hashCode = hashCode * 59 + this.Property.GetHashCode(); - hashCode = hashCode * 59 + this._123Number.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Property.GetHashCode(); + } + hashCode = (hashCode * 59) + this._123Number.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs index d7dedf8a391..0b61fdc69e6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs @@ -143,7 +143,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); @@ -201,29 +201,53 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.IntegerProp != null) - hashCode = hashCode * 59 + this.IntegerProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); + } if (this.NumberProp != null) - hashCode = hashCode * 59 + this.NumberProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); + } if (this.BooleanProp != null) - hashCode = hashCode * 59 + this.BooleanProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); + } if (this.StringProp != null) - hashCode = hashCode * 59 + this.StringProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); + } if (this.DateProp != null) - hashCode = hashCode * 59 + this.DateProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); + } if (this.DatetimeProp != null) - hashCode = hashCode * 59 + this.DatetimeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); + } if (this.ArrayNullableProp != null) - hashCode = hashCode * 59 + this.ArrayNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); + } if (this.ArrayAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ArrayAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); + } if (this.ArrayItemsNullable != null) - hashCode = hashCode * 59 + this.ArrayItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); + } if (this.ObjectNullableProp != null) - hashCode = hashCode * 59 + this.ObjectNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); + } if (this.ObjectAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ObjectAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); + } if (this.ObjectItemsNullable != null) - hashCode = hashCode * 59 + this.ObjectItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs index 54a8fa8e9fa..15281d72033 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NumberOnly {\n"); sb.Append(" JustNumber: ").Append(JustNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.JustNumber.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 2a33350b283..c313e46180f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -88,7 +88,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ObjectWithDeprecatedFields {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); @@ -138,14 +138,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); - hashCode = hashCode * 59 + this.Id.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.DeprecatedRef != null) - hashCode = hashCode * 59 + this.DeprecatedRef.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); + } if (this.Bars != null) - hashCode = hashCode * 59 + this.Bars.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bars.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs index c4c2bd17cca..5dbf90d5ef3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Order.cs @@ -129,7 +129,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); @@ -180,15 +180,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); - hashCode = hashCode * 59 + this.PetId.GetHashCode(); - hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.PetId.GetHashCode(); + hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); if (this.ShipDate != null) - hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); - hashCode = hashCode * 59 + this.Complete.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + hashCode = (hashCode * 59) + this.Complete.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs index 00fd62fb3a0..2351bbd1e53 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class OuterComposite {\n"); sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); sb.Append(" MyString: ").Append(MyString).Append("\n"); @@ -125,12 +125,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.MyNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.MyNumber.GetHashCode(); if (this.MyString != null) - hashCode = hashCode * 59 + this.MyString.GetHashCode(); - hashCode = hashCode * 59 + this.MyBoolean.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MyString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs index ff03e56a6f4..423c6e4e408 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ParentPet.cs @@ -65,7 +65,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ParentPet {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -112,7 +112,9 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -134,7 +136,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs index 0e5cc36e69c..8df973cda4e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Pet.cs @@ -145,7 +145,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Category: ").Append(Category).Append("\n"); @@ -196,18 +196,28 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Category != null) - hashCode = hashCode * 59 + this.Category.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Category.GetHashCode(); + } if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.PhotoUrls != null) - hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); + } if (this.Tags != null) - hashCode = hashCode * 59 + this.Tags.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Tags.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index 2b4c27fafe8..c9f98c3a79f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class QuadrilateralInterface {\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,9 +120,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 8dd9ba191fa..81adfe7489b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -75,7 +75,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ReadOnlyFirst {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Baz: ").Append(Baz).Append("\n"); @@ -123,11 +123,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Baz != null) - hashCode = hashCode * 59 + this.Baz.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Baz.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs index cac3f1b9b3d..b08ff811705 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Return.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Return {\n"); sb.Append(" _Return: ").Append(_Return).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Return.GetHashCode(); + hashCode = (hashCode * 59) + this._Return.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 94d6c80d998..5ae953e4f60 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ScaleneTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -133,11 +133,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs index b6307c94ddc..a723696e0aa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ShapeInterface {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,9 +120,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 2d0d58b4a08..b706f718758 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SimpleQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -133,11 +133,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs index 87f4023d689..d35b2d2d298 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SpecialModelName {\n"); sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); sb.Append(" _SpecialModelName: ").Append(_SpecialModelName).Append("\n"); @@ -116,11 +116,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.SpecialPropertyName.GetHashCode(); + hashCode = (hashCode * 59) + this.SpecialPropertyName.GetHashCode(); if (this._SpecialModelName != null) - hashCode = hashCode * 59 + this._SpecialModelName.GetHashCode(); + { + hashCode = (hashCode * 59) + this._SpecialModelName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs index 59f153e7096..3323ce57e28 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Tag.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Tag {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -116,11 +116,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs index 43ca1ed7979..3438ca5aabb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -73,7 +73,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class TriangleInterface {\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,9 +120,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs index 5edf8bc42bc..d099e469095 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/User.cs @@ -154,7 +154,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); @@ -211,30 +211,52 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Username != null) - hashCode = hashCode * 59 + this.Username.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Username.GetHashCode(); + } if (this.FirstName != null) - hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); + } if (this.LastName != null) - hashCode = hashCode * 59 + this.LastName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.LastName.GetHashCode(); + } if (this.Email != null) - hashCode = hashCode * 59 + this.Email.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Email.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.Phone != null) - hashCode = hashCode * 59 + this.Phone.GetHashCode(); - hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Phone.GetHashCode(); + } + hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); if (this.ObjectWithNoDeclaredProps != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredProps.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); + } if (this.ObjectWithNoDeclaredPropsNullable != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + } if (this.AnyTypeProp != null) - hashCode = hashCode * 59 + this.AnyTypeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); + } if (this.AnyTypePropNullable != null) - hashCode = hashCode * 59 + this.AnyTypePropNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs index 1a2f7783d7c..2c77472b9d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Whale.cs @@ -89,7 +89,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Whale {\n"); sb.Append(" HasBaleen: ").Append(HasBaleen).Append("\n"); sb.Append(" HasTeeth: ").Append(HasTeeth).Append("\n"); @@ -137,12 +137,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.HasBaleen.GetHashCode(); - hashCode = hashCode * 59 + this.HasTeeth.GetHashCode(); + hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); + hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs index 74c97732f6d..7ab15adf880 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs @@ -107,7 +107,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -155,11 +155,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Type.GetHashCode(); + hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index ad48306e00c..ac8fbdcdc94 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,21 +237,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/another-fake/dummy", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -279,7 +289,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -293,24 +305,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/another-fake/dummy", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs index 8844aca4ab7..a9e5cfb9c4d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -221,20 +221,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/foo", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -271,23 +279,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/foo", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs index dab406002f8..57a99469634 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs @@ -945,20 +945,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/fake/health", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -995,23 +1003,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/health", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1049,21 +1064,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/boolean", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1103,24 +1126,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/boolean", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1158,21 +1188,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/composite", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1212,24 +1250,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/composite", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1267,21 +1312,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/number", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1321,24 +1374,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/number", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1376,21 +1436,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/string", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1430,24 +1498,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/string", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1482,20 +1557,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get>("/fake/array-of-enums", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1532,23 +1615,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/fake/array-of-enums", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1575,7 +1665,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1588,21 +1680,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1631,7 +1731,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1644,24 +1746,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1690,11 +1799,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1707,10 +1820,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; @@ -1718,11 +1837,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-query-params", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1753,11 +1874,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1770,25 +1895,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-query-params", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1816,7 +1948,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1830,21 +1964,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1874,7 +2016,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1888,24 +2032,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1958,11 +2109,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1975,10 +2130,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2034,11 +2195,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2093,11 +2256,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2110,12 +2277,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2170,13 +2342,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2226,10 +2400,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2267,11 +2447,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2323,12 +2505,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2365,13 +2552,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2416,10 +2605,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2446,11 +2641,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2497,12 +2694,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2528,13 +2730,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2561,7 +2765,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2574,21 +2780,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request var localVarResponse = this.Client.Post("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2617,7 +2831,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2630,24 +2846,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2676,11 +2899,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2693,10 +2920,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter @@ -2704,11 +2937,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake/jsonFormData", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2739,11 +2974,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2756,25 +2995,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/jsonFormData", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2809,23 +3055,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2837,10 +3093,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2851,11 +3113,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/test-query-parameters", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2892,23 +3156,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2920,12 +3194,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2935,13 +3214,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/test-query-parameters", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index d4fbb5868ad..c2852b36a44 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,10 +237,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -250,11 +258,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Patch("/fake_classname_test", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -284,7 +294,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -298,12 +310,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -314,13 +331,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake_classname_test", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs index d73282dfca5..39d2e425e63 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs @@ -586,7 +586,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -600,10 +602,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -632,11 +640,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -665,7 +675,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -679,12 +691,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -712,13 +729,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -755,10 +774,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -775,11 +800,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -818,12 +845,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -839,13 +871,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -873,7 +907,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -887,10 +923,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -919,11 +961,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByStatus", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -953,7 +997,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -967,12 +1013,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -1000,13 +1051,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1036,7 +1089,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1050,10 +1105,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1082,11 +1143,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByTags", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1118,7 +1181,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1132,12 +1197,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1165,13 +1235,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1209,10 +1281,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1224,11 +1302,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1268,12 +1348,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1284,13 +1369,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1317,7 +1404,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1420,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1363,11 +1458,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1396,7 +1493,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1410,12 +1509,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1443,13 +1547,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1489,10 +1595,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1513,11 +1625,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1559,12 +1673,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1584,13 +1703,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1632,10 +1753,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1656,11 +1783,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1704,12 +1833,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1729,13 +1863,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1767,7 +1903,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1781,10 +1919,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1802,11 +1946,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1840,7 +1986,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1854,12 +2002,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1876,13 +2029,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs index ad7387db705..7cda385b3b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/StoreApi.cs @@ -345,7 +345,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -357,21 +359,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -400,7 +410,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -412,24 +424,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -464,10 +483,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -478,11 +503,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/store/inventory", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -519,12 +546,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -534,13 +566,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/store/inventory", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -578,21 +612,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -632,24 +674,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -677,7 +726,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -692,21 +743,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request var localVarResponse = this.Client.Post("/store/order", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -736,7 +795,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -751,24 +812,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/store/order", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs index a2f2598c8ac..a1716303f6f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Api/UserApi.cs @@ -517,7 +517,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -530,21 +532,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -573,7 +583,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -586,24 +598,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -630,7 +649,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -643,21 +664,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithArray", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -686,7 +715,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -699,24 +730,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithArray", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -743,7 +781,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -756,21 +796,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithList", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -799,7 +847,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -812,24 +862,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithList", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -856,7 +913,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -868,21 +927,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -911,7 +978,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -923,24 +992,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -968,7 +1044,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -982,21 +1060,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1026,7 +1112,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1040,24 +1128,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1087,11 +1182,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1105,10 +1204,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); @@ -1116,11 +1221,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/user/login", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1152,11 +1259,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1170,25 +1281,32 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/login", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1221,20 +1339,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/user/logout", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1269,23 +1395,30 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/logout", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1314,11 +1447,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1468,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; @@ -1342,11 +1485,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1377,11 +1522,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1394,25 +1543,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 9d6d049ded8..b3ddad35a07 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -117,7 +117,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); @@ -171,23 +171,41 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapProperty != null) - hashCode = hashCode * 59 + this.MapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); + } if (this.MapOfMapProperty != null) - hashCode = hashCode * 59 + this.MapOfMapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); + } if (this.Anytype1 != null) - hashCode = hashCode * 59 + this.Anytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype1 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype2 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype3 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + } if (this.EmptyMap != null) - hashCode = hashCode * 59 + this.EmptyMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesString != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Animal.cs index fd7599d09ca..e8ea00bb46a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Animal.cs @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Animal {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Color: ").Append(Color).Append("\n"); @@ -133,11 +133,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.Color != null) - hashCode = hashCode * 59 + this.Color.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Color.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ApiResponse.cs index ff7d757270f..79873f4ddfe 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -124,13 +124,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Code.GetHashCode(); + hashCode = (hashCode * 59) + this.Code.GetHashCode(); if (this.Type != null) - hashCode = hashCode * 59 + this.Type.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } if (this.Message != null) - hashCode = hashCode * 59 + this.Message.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Message.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Apple.cs index a702a9ca79f..8b1f87d1aa9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Apple.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Apple {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Origin: ").Append(Origin).Append("\n"); @@ -116,11 +116,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } if (this.Origin != null) - hashCode = hashCode * 59 + this.Origin.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Origin.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AppleReq.cs index 91a8d5c3aeb..1d6d42dc9b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/AppleReq.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AppleReq {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Mealy: ").Append(Mealy).Append("\n"); @@ -117,8 +117,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); - hashCode = hashCode * 59 + this.Mealy.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index e96382b222d..30bf57ef0f5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfArrayOfNumberOnly {\n"); sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 60c5a857656..8a215aad133 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfNumberOnly {\n"); sb.Append(" ArrayNumber: ").Append(ArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayTest.cs index 290926768d2..1a879a1d9ca 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayTest {\n"); sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); @@ -125,13 +125,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayOfString != null) - hashCode = hashCode * 59 + this.ArrayOfString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); + } if (this.ArrayArrayOfInteger != null) - hashCode = hashCode * 59 + this.ArrayArrayOfInteger.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); + } if (this.ArrayArrayOfModel != null) - hashCode = hashCode * 59 + this.ArrayArrayOfModel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Banana.cs index dc0e10d4686..97939597ede 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Banana.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Banana {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BananaReq.cs index ea57bb4f0cc..fdd36929d13 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BananaReq.cs @@ -66,7 +66,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BananaReq {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" Sweet: ").Append(Sweet).Append("\n"); @@ -112,8 +112,8 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); - hashCode = hashCode * 59 + this.Sweet.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BasquePig.cs index f9074c95c04..ea4ff737c89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/BasquePig.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BasquePig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Capitalization.cs index 3a989f765f9..be68a50a116 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Capitalization.cs @@ -101,7 +101,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Capitalization {\n"); sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); @@ -153,19 +153,33 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SmallCamel != null) - hashCode = hashCode * 59 + this.SmallCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); + } if (this.CapitalCamel != null) - hashCode = hashCode * 59 + this.CapitalCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); + } if (this.SmallSnake != null) - hashCode = hashCode * 59 + this.SmallSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); + } if (this.CapitalSnake != null) - hashCode = hashCode * 59 + this.CapitalSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); + } if (this.SCAETHFlowPoints != null) - hashCode = hashCode * 59 + this.SCAETHFlowPoints.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); + } if (this.ATT_NAME != null) - hashCode = hashCode * 59 + this.ATT_NAME.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Cat.cs index be96bae85eb..2bc55707da9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Cat.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Cat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); @@ -119,9 +119,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -143,7 +145,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/CatAllOf.cs index 8cb5bfc3ef6..3a960e9925e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class CatAllOf {\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Category.cs index 6b0b74ca521..0cc23f5f6c2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Category.cs @@ -80,7 +80,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -127,11 +127,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs index 90545c4d99a..7a15a5297df 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs @@ -92,7 +92,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -141,10 +141,14 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -166,7 +170,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index b5d479e1742..a353ad7ffd7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -82,7 +82,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCatAllOf {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); @@ -130,10 +130,14 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ClassModel.cs index 80c863484cc..7177e9bf0b6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ClassModel.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ClassModel {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index f3afcc2a734..807f0eb26bf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ComplexQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DanishPig.cs index 59afe7580d0..a27b1db3929 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DanishPig.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DanishPig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DeprecatedObject.cs index bd3d97b081d..1928b236bf6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DeprecatedObject {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Dog.cs index f20af26112c..9cd520deaf8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Dog.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Dog {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); @@ -120,9 +120,13 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -144,7 +148,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DogAllOf.cs index 3588b02b020..7b026acbf1e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DogAllOf {\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs index f7e6702be59..d8cd2a70ef6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); @@ -127,13 +127,21 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.MainShape != null) - hashCode = hashCode * 59 + this.MainShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); + } if (this.ShapeOrNull != null) - hashCode = hashCode * 59 + this.ShapeOrNull.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); + } if (this.NullableShape != null) - hashCode = hashCode * 59 + this.NullableShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); + } if (this.Shapes != null) - hashCode = hashCode * 59 + this.Shapes.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumArrays.cs index f4138fce032..6d7830c0e8b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumArrays {\n"); sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); sb.Append(" ArrayEnum: ").Append(ArrayEnum).Append("\n"); @@ -156,10 +156,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustSymbol.GetHashCode(); - hashCode = hashCode * 59 + this.ArrayEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumTest.cs index 178d540314d..6f3d2272c5c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EnumTest.cs @@ -238,7 +238,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); @@ -292,17 +292,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.EnumString.GetHashCode(); - hashCode = hashCode * 59 + this.EnumStringRequired.GetHashCode(); - hashCode = hashCode * 59 + this.EnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.EnumIntegerOnly.GetHashCode(); - hashCode = hashCode * 59 + this.EnumNumber.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnum.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumDefaultValue.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumIntegerDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumStringRequired.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 2e8e4d0c17d..a931c0d6327 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EquilateralTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/File.cs index 1e859462b14..e77d15e06bc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/File.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class File {\n"); sb.Append(" SourceURI: ").Append(SourceURI).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SourceURI != null) - hashCode = hashCode * 59 + this.SourceURI.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index b996e287ea7..6808978c49f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FileSchemaTestClass {\n"); sb.Append(" File: ").Append(File).Append("\n"); sb.Append(" Files: ").Append(Files).Append("\n"); @@ -116,11 +116,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); + { + hashCode = (hashCode * 59) + this.File.GetHashCode(); + } if (this.Files != null) - hashCode = hashCode * 59 + this.Files.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Files.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Foo.cs index a5aabbae4f3..e64aac7b631 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Foo.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Foo {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FormatTest.cs index ef60b6bb9fe..eb38d586bbb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/FormatTest.cs @@ -199,7 +199,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); @@ -260,33 +260,53 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Integer.GetHashCode(); - hashCode = hashCode * 59 + this.Int32.GetHashCode(); - hashCode = hashCode * 59 + this.Int64.GetHashCode(); - hashCode = hashCode * 59 + this.Number.GetHashCode(); - hashCode = hashCode * 59 + this.Float.GetHashCode(); - hashCode = hashCode * 59 + this.Double.GetHashCode(); - hashCode = hashCode * 59 + this.Decimal.GetHashCode(); + hashCode = (hashCode * 59) + this.Integer.GetHashCode(); + hashCode = (hashCode * 59) + this.Int32.GetHashCode(); + hashCode = (hashCode * 59) + this.Int64.GetHashCode(); + hashCode = (hashCode * 59) + this.Number.GetHashCode(); + hashCode = (hashCode * 59) + this.Float.GetHashCode(); + hashCode = (hashCode * 59) + this.Double.GetHashCode(); + hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.Byte != null) - hashCode = hashCode * 59 + this.Byte.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Byte.GetHashCode(); + } if (this.Binary != null) - hashCode = hashCode * 59 + this.Binary.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Binary.GetHashCode(); + } if (this.Date != null) - hashCode = hashCode * 59 + this.Date.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Date.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.PatternWithDigits != null) - hashCode = hashCode * 59 + this.PatternWithDigits.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); + } if (this.PatternWithDigitsAndDelimiter != null) - hashCode = hashCode * 59 + this.PatternWithDigitsAndDelimiter.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -299,61 +319,61 @@ namespace Org.OpenAPITools.Model public IEnumerable Validate(ValidationContext validationContext) { // Integer (int) maximum - if(this.Integer > (int)100) + if (this.Integer > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if(this.Integer < (int)10) + if (this.Integer < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } // Int32 (int) maximum - if(this.Int32 > (int)200) + if (this.Int32 > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if(this.Int32 < (int)20) + if (this.Int32 < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Number (decimal) maximum - if(this.Number > (decimal)543.2) + if (this.Number > (decimal)543.2) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); } // Number (decimal) minimum - if(this.Number < (decimal)32.1) + if (this.Number < (decimal)32.1) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); } // Float (float) maximum - if(this.Float > (float)987.6) + if (this.Float > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); } // Float (float) minimum - if(this.Float < (float)54.3) + if (this.Float < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); } // Double (double) maximum - if(this.Double > (double)123.4) + if (this.Double > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); } // Double (double) minimum - if(this.Double < (double)67.8) + if (this.Double < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); } @@ -366,13 +386,13 @@ namespace Org.OpenAPITools.Model } // Password (string) maxLength - if(this.Password != null && this.Password.Length > 64) + if (this.Password != null && this.Password.Length > 64) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); } // Password (string) minLength - if(this.Password != null && this.Password.Length < 10) + if (this.Password != null && this.Password.Length < 10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 9edacb3815a..cee75f3f815 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class GrandparentAnimal {\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -123,9 +123,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.PetType != null) - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index f6219182b29..52099a7095e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -81,7 +81,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HasOnlyReadOnly {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Foo: ").Append(Foo).Append("\n"); @@ -129,11 +129,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Foo != null) - hashCode = hashCode * 59 + this.Foo.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Foo.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HealthCheckResult.cs index c7c342d258a..e8cbb68e2e4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HealthCheckResult {\n"); sb.Append(" NullableMessage: ").Append(NullableMessage).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.NullableMessage != null) - hashCode = hashCode * 59 + this.NullableMessage.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineResponseDefault.cs index e492ade1fc6..ae46f1f0098 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/InlineResponseDefault.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponseDefault {\n"); sb.Append(" String: ").Append(String).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 8d02354be3f..50e7ce4aaa8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class IsoscelesTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/List.cs index 5f3483a6e30..00814d11069 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/List.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class List {\n"); sb.Append(" _123List: ").Append(_123List).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._123List != null) - hashCode = hashCode * 59 + this._123List.GetHashCode(); + { + hashCode = (hashCode * 59) + this._123List.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MapTest.cs index fa93bf24ec0..8b5a73e7736 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MapTest.cs @@ -105,7 +105,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MapTest {\n"); sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); @@ -155,14 +155,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapMapOfString != null) - hashCode = hashCode * 59 + this.MapMapOfString.GetHashCode(); - hashCode = hashCode * 59 + this.MapOfEnumString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); if (this.DirectMap != null) - hashCode = hashCode * 59 + this.DirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); + } if (this.IndirectMap != null) - hashCode = hashCode * 59 + this.IndirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 8853f837f9e..3225727af37 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); @@ -125,13 +125,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Map != null) - hashCode = hashCode * 59 + this.Map.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Map.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Model200Response.cs index 629a1fde7fb..79a49ef91d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Model200Response.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Model200Response {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); @@ -115,11 +115,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = (hashCode * 59) + this.Name.GetHashCode(); if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ModelClient.cs index e28bc67d630..1995ec4b169 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ModelClient.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ModelClient {\n"); sb.Append(" _Client: ").Append(_Client).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._Client != null) - hashCode = hashCode * 59 + this._Client.GetHashCode(); + { + hashCode = (hashCode * 59) + this._Client.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs index 462b3458215..0dc21bb656f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Name.cs @@ -104,7 +104,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" _Name: ").Append(_Name).Append("\n"); sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); @@ -153,13 +153,17 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Name.GetHashCode(); - hashCode = hashCode * 59 + this.SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + this._Name.GetHashCode(); + hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); if (this.Property != null) - hashCode = hashCode * 59 + this.Property.GetHashCode(); - hashCode = hashCode * 59 + this._123Number.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Property.GetHashCode(); + } + hashCode = (hashCode * 59) + this._123Number.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs index 3a34e8cc128..57555c37678 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs @@ -142,7 +142,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); @@ -200,29 +200,53 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.IntegerProp != null) - hashCode = hashCode * 59 + this.IntegerProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); + } if (this.NumberProp != null) - hashCode = hashCode * 59 + this.NumberProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); + } if (this.BooleanProp != null) - hashCode = hashCode * 59 + this.BooleanProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); + } if (this.StringProp != null) - hashCode = hashCode * 59 + this.StringProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); + } if (this.DateProp != null) - hashCode = hashCode * 59 + this.DateProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); + } if (this.DatetimeProp != null) - hashCode = hashCode * 59 + this.DatetimeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); + } if (this.ArrayNullableProp != null) - hashCode = hashCode * 59 + this.ArrayNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); + } if (this.ArrayAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ArrayAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); + } if (this.ArrayItemsNullable != null) - hashCode = hashCode * 59 + this.ArrayItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); + } if (this.ObjectNullableProp != null) - hashCode = hashCode * 59 + this.ObjectNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); + } if (this.ObjectAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ObjectAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); + } if (this.ObjectItemsNullable != null) - hashCode = hashCode * 59 + this.ObjectItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NumberOnly.cs index 34abb32eabd..97f869b0ebc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NumberOnly {\n"); sb.Append(" JustNumber: ").Append(JustNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.JustNumber.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 021bfe71e02..86ea32998f8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -87,7 +87,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ObjectWithDeprecatedFields {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); @@ -137,14 +137,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); - hashCode = hashCode * 59 + this.Id.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.DeprecatedRef != null) - hashCode = hashCode * 59 + this.DeprecatedRef.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); + } if (this.Bars != null) - hashCode = hashCode * 59 + this.Bars.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bars.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Order.cs index e1abd07a05c..5c52482e79b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Order.cs @@ -128,7 +128,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); @@ -179,15 +179,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); - hashCode = hashCode * 59 + this.PetId.GetHashCode(); - hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.PetId.GetHashCode(); + hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); if (this.ShipDate != null) - hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); - hashCode = hashCode * 59 + this.Complete.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + hashCode = (hashCode * 59) + this.Complete.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/OuterComposite.cs index 88449a1c843..3209f6d6244 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class OuterComposite {\n"); sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); sb.Append(" MyString: ").Append(MyString).Append("\n"); @@ -124,12 +124,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.MyNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.MyNumber.GetHashCode(); if (this.MyString != null) - hashCode = hashCode * 59 + this.MyString.GetHashCode(); - hashCode = hashCode * 59 + this.MyBoolean.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MyString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ParentPet.cs index 899984fcc5b..ac986b555ef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ParentPet.cs @@ -64,7 +64,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ParentPet {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -111,7 +111,9 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -133,7 +135,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pet.cs index 8b3b614493f..31fd118f4f6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Pet.cs @@ -144,7 +144,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Category: ").Append(Category).Append("\n"); @@ -195,18 +195,28 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Category != null) - hashCode = hashCode * 59 + this.Category.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Category.GetHashCode(); + } if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.PhotoUrls != null) - hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); + } if (this.Tags != null) - hashCode = hashCode * 59 + this.Tags.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Tags.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index de200d38d54..4d7c39c4364 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class QuadrilateralInterface {\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 08a294a2290..ad59ca83286 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ReadOnlyFirst {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Baz: ").Append(Baz).Append("\n"); @@ -122,11 +122,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Baz != null) - hashCode = hashCode * 59 + this.Baz.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Baz.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Return.cs index 74317fbbfec..e702e015703 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Return.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Return {\n"); sb.Append(" _Return: ").Append(_Return).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Return.GetHashCode(); + hashCode = (hashCode * 59) + this._Return.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 6b4869ce839..23683947147 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ScaleneTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeInterface.cs index ccd305b4509..92774561aaa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ShapeInterface {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index d698a788f8e..fc9b37ce01f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SimpleQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SpecialModelName.cs index 1d6445d4d62..7800467822e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SpecialModelName {\n"); sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); sb.Append(" _SpecialModelName: ").Append(_SpecialModelName).Append("\n"); @@ -115,11 +115,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.SpecialPropertyName.GetHashCode(); + hashCode = (hashCode * 59) + this.SpecialPropertyName.GetHashCode(); if (this._SpecialModelName != null) - hashCode = hashCode * 59 + this._SpecialModelName.GetHashCode(); + { + hashCode = (hashCode * 59) + this._SpecialModelName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Tag.cs index 2635acce4e4..3df2c02e2ce 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Tag.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Tag {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -115,11 +115,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TriangleInterface.cs index 14bd3a6724c..7f7abb5bc85 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class TriangleInterface {\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/User.cs index ebd632a90ac..5f2a3020c3d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/User.cs @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); @@ -210,30 +210,52 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Username != null) - hashCode = hashCode * 59 + this.Username.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Username.GetHashCode(); + } if (this.FirstName != null) - hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); + } if (this.LastName != null) - hashCode = hashCode * 59 + this.LastName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.LastName.GetHashCode(); + } if (this.Email != null) - hashCode = hashCode * 59 + this.Email.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Email.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.Phone != null) - hashCode = hashCode * 59 + this.Phone.GetHashCode(); - hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Phone.GetHashCode(); + } + hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); if (this.ObjectWithNoDeclaredProps != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredProps.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); + } if (this.ObjectWithNoDeclaredPropsNullable != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + } if (this.AnyTypeProp != null) - hashCode = hashCode * 59 + this.AnyTypeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); + } if (this.AnyTypePropNullable != null) - hashCode = hashCode * 59 + this.AnyTypePropNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Whale.cs index 57ef3850e97..c30b6dbfabe 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Whale.cs @@ -88,7 +88,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Whale {\n"); sb.Append(" HasBaleen: ").Append(HasBaleen).Append("\n"); sb.Append(" HasTeeth: ").Append(HasTeeth).Append("\n"); @@ -136,12 +136,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.HasBaleen.GetHashCode(); - hashCode = hashCode * 59 + this.HasTeeth.GetHashCode(); + hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); + hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs index bf9735fb37e..4fb60ed8ddf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs @@ -106,7 +106,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -154,11 +154,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Type.GetHashCode(); + hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index ad48306e00c..ac8fbdcdc94 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,21 +237,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/another-fake/dummy", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -279,7 +289,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -293,24 +305,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/another-fake/dummy", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs index 8844aca4ab7..a9e5cfb9c4d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -221,20 +221,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/foo", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -271,23 +279,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/foo", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs index dab406002f8..57a99469634 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs @@ -945,20 +945,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/fake/health", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -995,23 +1003,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/health", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1049,21 +1064,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/boolean", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1103,24 +1126,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/boolean", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1158,21 +1188,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/composite", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1212,24 +1250,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/composite", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1267,21 +1312,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/number", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1321,24 +1374,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/number", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1376,21 +1436,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/string", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1430,24 +1498,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/string", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1482,20 +1557,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get>("/fake/array-of-enums", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1532,23 +1615,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/fake/array-of-enums", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1575,7 +1665,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1588,21 +1680,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1631,7 +1731,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1644,24 +1746,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1690,11 +1799,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1707,10 +1820,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; @@ -1718,11 +1837,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-query-params", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1753,11 +1874,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1770,25 +1895,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-query-params", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1816,7 +1948,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1830,21 +1964,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1874,7 +2016,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1888,24 +2032,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1958,11 +2109,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1975,10 +2130,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2034,11 +2195,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2093,11 +2256,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2110,12 +2277,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2170,13 +2342,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2226,10 +2400,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2267,11 +2447,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2323,12 +2505,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2365,13 +2552,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2416,10 +2605,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2446,11 +2641,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2497,12 +2694,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2528,13 +2730,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2561,7 +2765,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2574,21 +2780,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request var localVarResponse = this.Client.Post("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2617,7 +2831,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2630,24 +2846,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2676,11 +2899,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2693,10 +2920,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter @@ -2704,11 +2937,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake/jsonFormData", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2739,11 +2974,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2756,25 +2995,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/jsonFormData", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2809,23 +3055,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2837,10 +3093,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2851,11 +3113,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/test-query-parameters", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2892,23 +3156,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2920,12 +3194,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2935,13 +3214,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/test-query-parameters", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index d4fbb5868ad..c2852b36a44 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,10 +237,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -250,11 +258,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Patch("/fake_classname_test", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -284,7 +294,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -298,12 +310,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -314,13 +331,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake_classname_test", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs index d73282dfca5..39d2e425e63 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs @@ -586,7 +586,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -600,10 +602,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -632,11 +640,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -665,7 +675,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -679,12 +691,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -712,13 +729,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -755,10 +774,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -775,11 +800,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -818,12 +845,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -839,13 +871,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -873,7 +907,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -887,10 +923,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -919,11 +961,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByStatus", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -953,7 +997,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -967,12 +1013,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -1000,13 +1051,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1036,7 +1089,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1050,10 +1105,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1082,11 +1143,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByTags", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1118,7 +1181,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1132,12 +1197,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1165,13 +1235,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1209,10 +1281,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1224,11 +1302,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1268,12 +1348,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1284,13 +1369,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1317,7 +1404,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1420,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1363,11 +1458,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1396,7 +1493,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1410,12 +1509,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1443,13 +1547,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1489,10 +1595,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1513,11 +1625,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1559,12 +1673,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1584,13 +1703,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1632,10 +1753,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1656,11 +1783,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1704,12 +1833,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1729,13 +1863,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1767,7 +1903,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1781,10 +1919,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1802,11 +1946,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1840,7 +1986,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1854,12 +2002,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1876,13 +2029,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs index ad7387db705..7cda385b3b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/StoreApi.cs @@ -345,7 +345,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -357,21 +359,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -400,7 +410,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -412,24 +424,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -464,10 +483,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -478,11 +503,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/store/inventory", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -519,12 +546,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -534,13 +566,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/store/inventory", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -578,21 +612,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -632,24 +674,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -677,7 +726,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -692,21 +743,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request var localVarResponse = this.Client.Post("/store/order", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -736,7 +795,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -751,24 +812,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/store/order", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs index a2f2598c8ac..a1716303f6f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/UserApi.cs @@ -517,7 +517,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -530,21 +532,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -573,7 +583,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -586,24 +598,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -630,7 +649,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -643,21 +664,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithArray", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -686,7 +715,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -699,24 +730,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithArray", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -743,7 +781,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -756,21 +796,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithList", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -799,7 +847,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -812,24 +862,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithList", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -856,7 +913,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -868,21 +927,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -911,7 +978,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -923,24 +992,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -968,7 +1044,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -982,21 +1060,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1026,7 +1112,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1040,24 +1128,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1087,11 +1182,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1105,10 +1204,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); @@ -1116,11 +1221,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/user/login", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1152,11 +1259,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1170,25 +1281,32 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/login", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1221,20 +1339,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/user/logout", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1269,23 +1395,30 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/logout", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1314,11 +1447,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1468,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; @@ -1342,11 +1485,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1377,11 +1522,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1394,25 +1543,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 9d6d049ded8..b3ddad35a07 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -117,7 +117,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); @@ -171,23 +171,41 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapProperty != null) - hashCode = hashCode * 59 + this.MapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); + } if (this.MapOfMapProperty != null) - hashCode = hashCode * 59 + this.MapOfMapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); + } if (this.Anytype1 != null) - hashCode = hashCode * 59 + this.Anytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype1 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype2 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype3 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + } if (this.EmptyMap != null) - hashCode = hashCode * 59 + this.EmptyMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesString != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Animal.cs index fd7599d09ca..e8ea00bb46a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Animal.cs @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Animal {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Color: ").Append(Color).Append("\n"); @@ -133,11 +133,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.Color != null) - hashCode = hashCode * 59 + this.Color.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Color.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ApiResponse.cs index ff7d757270f..79873f4ddfe 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -124,13 +124,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Code.GetHashCode(); + hashCode = (hashCode * 59) + this.Code.GetHashCode(); if (this.Type != null) - hashCode = hashCode * 59 + this.Type.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } if (this.Message != null) - hashCode = hashCode * 59 + this.Message.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Message.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Apple.cs index a702a9ca79f..8b1f87d1aa9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Apple.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Apple {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Origin: ").Append(Origin).Append("\n"); @@ -116,11 +116,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } if (this.Origin != null) - hashCode = hashCode * 59 + this.Origin.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Origin.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AppleReq.cs index 91a8d5c3aeb..1d6d42dc9b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/AppleReq.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AppleReq {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Mealy: ").Append(Mealy).Append("\n"); @@ -117,8 +117,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); - hashCode = hashCode * 59 + this.Mealy.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index e96382b222d..30bf57ef0f5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfArrayOfNumberOnly {\n"); sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 60c5a857656..8a215aad133 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfNumberOnly {\n"); sb.Append(" ArrayNumber: ").Append(ArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayTest.cs index 290926768d2..1a879a1d9ca 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayTest {\n"); sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); @@ -125,13 +125,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayOfString != null) - hashCode = hashCode * 59 + this.ArrayOfString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); + } if (this.ArrayArrayOfInteger != null) - hashCode = hashCode * 59 + this.ArrayArrayOfInteger.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); + } if (this.ArrayArrayOfModel != null) - hashCode = hashCode * 59 + this.ArrayArrayOfModel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Banana.cs index dc0e10d4686..97939597ede 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Banana.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Banana {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BananaReq.cs index ea57bb4f0cc..fdd36929d13 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BananaReq.cs @@ -66,7 +66,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BananaReq {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" Sweet: ").Append(Sweet).Append("\n"); @@ -112,8 +112,8 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); - hashCode = hashCode * 59 + this.Sweet.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BasquePig.cs index f9074c95c04..ea4ff737c89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/BasquePig.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BasquePig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Capitalization.cs index 3a989f765f9..be68a50a116 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Capitalization.cs @@ -101,7 +101,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Capitalization {\n"); sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); @@ -153,19 +153,33 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SmallCamel != null) - hashCode = hashCode * 59 + this.SmallCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); + } if (this.CapitalCamel != null) - hashCode = hashCode * 59 + this.CapitalCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); + } if (this.SmallSnake != null) - hashCode = hashCode * 59 + this.SmallSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); + } if (this.CapitalSnake != null) - hashCode = hashCode * 59 + this.CapitalSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); + } if (this.SCAETHFlowPoints != null) - hashCode = hashCode * 59 + this.SCAETHFlowPoints.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); + } if (this.ATT_NAME != null) - hashCode = hashCode * 59 + this.ATT_NAME.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Cat.cs index be96bae85eb..2bc55707da9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Cat.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Cat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); @@ -119,9 +119,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -143,7 +145,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/CatAllOf.cs index 8cb5bfc3ef6..3a960e9925e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class CatAllOf {\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Category.cs index 6b0b74ca521..0cc23f5f6c2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Category.cs @@ -80,7 +80,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -127,11 +127,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs index 90545c4d99a..7a15a5297df 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs @@ -92,7 +92,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -141,10 +141,14 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -166,7 +170,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index b5d479e1742..a353ad7ffd7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -82,7 +82,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCatAllOf {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); @@ -130,10 +130,14 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ClassModel.cs index 80c863484cc..7177e9bf0b6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ClassModel.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ClassModel {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index f3afcc2a734..807f0eb26bf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ComplexQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DanishPig.cs index 59afe7580d0..a27b1db3929 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DanishPig.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DanishPig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs index bd3d97b081d..1928b236bf6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DeprecatedObject {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Dog.cs index f20af26112c..9cd520deaf8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Dog.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Dog {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); @@ -120,9 +120,13 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -144,7 +148,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DogAllOf.cs index 3588b02b020..7b026acbf1e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DogAllOf {\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs index f7e6702be59..d8cd2a70ef6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); @@ -127,13 +127,21 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.MainShape != null) - hashCode = hashCode * 59 + this.MainShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); + } if (this.ShapeOrNull != null) - hashCode = hashCode * 59 + this.ShapeOrNull.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); + } if (this.NullableShape != null) - hashCode = hashCode * 59 + this.NullableShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); + } if (this.Shapes != null) - hashCode = hashCode * 59 + this.Shapes.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumArrays.cs index f4138fce032..6d7830c0e8b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumArrays {\n"); sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); sb.Append(" ArrayEnum: ").Append(ArrayEnum).Append("\n"); @@ -156,10 +156,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustSymbol.GetHashCode(); - hashCode = hashCode * 59 + this.ArrayEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumTest.cs index 178d540314d..6f3d2272c5c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EnumTest.cs @@ -238,7 +238,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); @@ -292,17 +292,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.EnumString.GetHashCode(); - hashCode = hashCode * 59 + this.EnumStringRequired.GetHashCode(); - hashCode = hashCode * 59 + this.EnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.EnumIntegerOnly.GetHashCode(); - hashCode = hashCode * 59 + this.EnumNumber.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnum.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumDefaultValue.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumIntegerDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumStringRequired.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 2e8e4d0c17d..a931c0d6327 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EquilateralTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/File.cs index 1e859462b14..e77d15e06bc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/File.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class File {\n"); sb.Append(" SourceURI: ").Append(SourceURI).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SourceURI != null) - hashCode = hashCode * 59 + this.SourceURI.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index b996e287ea7..6808978c49f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FileSchemaTestClass {\n"); sb.Append(" File: ").Append(File).Append("\n"); sb.Append(" Files: ").Append(Files).Append("\n"); @@ -116,11 +116,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); + { + hashCode = (hashCode * 59) + this.File.GetHashCode(); + } if (this.Files != null) - hashCode = hashCode * 59 + this.Files.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Files.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Foo.cs index a5aabbae4f3..e64aac7b631 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Foo.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Foo {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs index ef60b6bb9fe..eb38d586bbb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs @@ -199,7 +199,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); @@ -260,33 +260,53 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Integer.GetHashCode(); - hashCode = hashCode * 59 + this.Int32.GetHashCode(); - hashCode = hashCode * 59 + this.Int64.GetHashCode(); - hashCode = hashCode * 59 + this.Number.GetHashCode(); - hashCode = hashCode * 59 + this.Float.GetHashCode(); - hashCode = hashCode * 59 + this.Double.GetHashCode(); - hashCode = hashCode * 59 + this.Decimal.GetHashCode(); + hashCode = (hashCode * 59) + this.Integer.GetHashCode(); + hashCode = (hashCode * 59) + this.Int32.GetHashCode(); + hashCode = (hashCode * 59) + this.Int64.GetHashCode(); + hashCode = (hashCode * 59) + this.Number.GetHashCode(); + hashCode = (hashCode * 59) + this.Float.GetHashCode(); + hashCode = (hashCode * 59) + this.Double.GetHashCode(); + hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.Byte != null) - hashCode = hashCode * 59 + this.Byte.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Byte.GetHashCode(); + } if (this.Binary != null) - hashCode = hashCode * 59 + this.Binary.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Binary.GetHashCode(); + } if (this.Date != null) - hashCode = hashCode * 59 + this.Date.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Date.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.PatternWithDigits != null) - hashCode = hashCode * 59 + this.PatternWithDigits.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); + } if (this.PatternWithDigitsAndDelimiter != null) - hashCode = hashCode * 59 + this.PatternWithDigitsAndDelimiter.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -299,61 +319,61 @@ namespace Org.OpenAPITools.Model public IEnumerable Validate(ValidationContext validationContext) { // Integer (int) maximum - if(this.Integer > (int)100) + if (this.Integer > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if(this.Integer < (int)10) + if (this.Integer < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } // Int32 (int) maximum - if(this.Int32 > (int)200) + if (this.Int32 > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if(this.Int32 < (int)20) + if (this.Int32 < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Number (decimal) maximum - if(this.Number > (decimal)543.2) + if (this.Number > (decimal)543.2) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); } // Number (decimal) minimum - if(this.Number < (decimal)32.1) + if (this.Number < (decimal)32.1) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); } // Float (float) maximum - if(this.Float > (float)987.6) + if (this.Float > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); } // Float (float) minimum - if(this.Float < (float)54.3) + if (this.Float < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); } // Double (double) maximum - if(this.Double > (double)123.4) + if (this.Double > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); } // Double (double) minimum - if(this.Double < (double)67.8) + if (this.Double < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); } @@ -366,13 +386,13 @@ namespace Org.OpenAPITools.Model } // Password (string) maxLength - if(this.Password != null && this.Password.Length > 64) + if (this.Password != null && this.Password.Length > 64) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); } // Password (string) minLength - if(this.Password != null && this.Password.Length < 10) + if (this.Password != null && this.Password.Length < 10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 9edacb3815a..cee75f3f815 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class GrandparentAnimal {\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -123,9 +123,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.PetType != null) - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index f6219182b29..52099a7095e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -81,7 +81,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HasOnlyReadOnly {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Foo: ").Append(Foo).Append("\n"); @@ -129,11 +129,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Foo != null) - hashCode = hashCode * 59 + this.Foo.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Foo.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs index c7c342d258a..e8cbb68e2e4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HealthCheckResult {\n"); sb.Append(" NullableMessage: ").Append(NullableMessage).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.NullableMessage != null) - hashCode = hashCode * 59 + this.NullableMessage.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs index e492ade1fc6..ae46f1f0098 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/InlineResponseDefault.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponseDefault {\n"); sb.Append(" String: ").Append(String).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 8d02354be3f..50e7ce4aaa8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class IsoscelesTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/List.cs index 5f3483a6e30..00814d11069 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/List.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class List {\n"); sb.Append(" _123List: ").Append(_123List).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._123List != null) - hashCode = hashCode * 59 + this._123List.GetHashCode(); + { + hashCode = (hashCode * 59) + this._123List.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MapTest.cs index fa93bf24ec0..8b5a73e7736 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MapTest.cs @@ -105,7 +105,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MapTest {\n"); sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); @@ -155,14 +155,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapMapOfString != null) - hashCode = hashCode * 59 + this.MapMapOfString.GetHashCode(); - hashCode = hashCode * 59 + this.MapOfEnumString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); if (this.DirectMap != null) - hashCode = hashCode * 59 + this.DirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); + } if (this.IndirectMap != null) - hashCode = hashCode * 59 + this.IndirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 8853f837f9e..3225727af37 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); @@ -125,13 +125,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Map != null) - hashCode = hashCode * 59 + this.Map.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Map.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Model200Response.cs index 629a1fde7fb..79a49ef91d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Model200Response.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Model200Response {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); @@ -115,11 +115,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = (hashCode * 59) + this.Name.GetHashCode(); if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ModelClient.cs index e28bc67d630..1995ec4b169 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ModelClient.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ModelClient {\n"); sb.Append(" _Client: ").Append(_Client).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._Client != null) - hashCode = hashCode * 59 + this._Client.GetHashCode(); + { + hashCode = (hashCode * 59) + this._Client.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs index 462b3458215..0dc21bb656f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Name.cs @@ -104,7 +104,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" _Name: ").Append(_Name).Append("\n"); sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); @@ -153,13 +153,17 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Name.GetHashCode(); - hashCode = hashCode * 59 + this.SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + this._Name.GetHashCode(); + hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); if (this.Property != null) - hashCode = hashCode * 59 + this.Property.GetHashCode(); - hashCode = hashCode * 59 + this._123Number.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Property.GetHashCode(); + } + hashCode = (hashCode * 59) + this._123Number.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs index 3a34e8cc128..57555c37678 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs @@ -142,7 +142,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); @@ -200,29 +200,53 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.IntegerProp != null) - hashCode = hashCode * 59 + this.IntegerProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); + } if (this.NumberProp != null) - hashCode = hashCode * 59 + this.NumberProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); + } if (this.BooleanProp != null) - hashCode = hashCode * 59 + this.BooleanProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); + } if (this.StringProp != null) - hashCode = hashCode * 59 + this.StringProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); + } if (this.DateProp != null) - hashCode = hashCode * 59 + this.DateProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); + } if (this.DatetimeProp != null) - hashCode = hashCode * 59 + this.DatetimeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); + } if (this.ArrayNullableProp != null) - hashCode = hashCode * 59 + this.ArrayNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); + } if (this.ArrayAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ArrayAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); + } if (this.ArrayItemsNullable != null) - hashCode = hashCode * 59 + this.ArrayItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); + } if (this.ObjectNullableProp != null) - hashCode = hashCode * 59 + this.ObjectNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); + } if (this.ObjectAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ObjectAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); + } if (this.ObjectItemsNullable != null) - hashCode = hashCode * 59 + this.ObjectItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NumberOnly.cs index 34abb32eabd..97f869b0ebc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NumberOnly {\n"); sb.Append(" JustNumber: ").Append(JustNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.JustNumber.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 021bfe71e02..86ea32998f8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -87,7 +87,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ObjectWithDeprecatedFields {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); @@ -137,14 +137,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); - hashCode = hashCode * 59 + this.Id.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.DeprecatedRef != null) - hashCode = hashCode * 59 + this.DeprecatedRef.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); + } if (this.Bars != null) - hashCode = hashCode * 59 + this.Bars.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bars.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Order.cs index e1abd07a05c..5c52482e79b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Order.cs @@ -128,7 +128,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); @@ -179,15 +179,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); - hashCode = hashCode * 59 + this.PetId.GetHashCode(); - hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.PetId.GetHashCode(); + hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); if (this.ShipDate != null) - hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); - hashCode = hashCode * 59 + this.Complete.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + hashCode = (hashCode * 59) + this.Complete.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterComposite.cs index 88449a1c843..3209f6d6244 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class OuterComposite {\n"); sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); sb.Append(" MyString: ").Append(MyString).Append("\n"); @@ -124,12 +124,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.MyNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.MyNumber.GetHashCode(); if (this.MyString != null) - hashCode = hashCode * 59 + this.MyString.GetHashCode(); - hashCode = hashCode * 59 + this.MyBoolean.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MyString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ParentPet.cs index 899984fcc5b..ac986b555ef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ParentPet.cs @@ -64,7 +64,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ParentPet {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -111,7 +111,9 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -133,7 +135,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pet.cs index 8b3b614493f..31fd118f4f6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Pet.cs @@ -144,7 +144,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Category: ").Append(Category).Append("\n"); @@ -195,18 +195,28 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Category != null) - hashCode = hashCode * 59 + this.Category.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Category.GetHashCode(); + } if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.PhotoUrls != null) - hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); + } if (this.Tags != null) - hashCode = hashCode * 59 + this.Tags.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Tags.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index de200d38d54..4d7c39c4364 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class QuadrilateralInterface {\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 08a294a2290..ad59ca83286 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ReadOnlyFirst {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Baz: ").Append(Baz).Append("\n"); @@ -122,11 +122,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Baz != null) - hashCode = hashCode * 59 + this.Baz.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Baz.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Return.cs index 74317fbbfec..e702e015703 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Return.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Return {\n"); sb.Append(" _Return: ").Append(_Return).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Return.GetHashCode(); + hashCode = (hashCode * 59) + this._Return.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 6b4869ce839..23683947147 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ScaleneTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeInterface.cs index ccd305b4509..92774561aaa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ShapeInterface {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index d698a788f8e..fc9b37ce01f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SimpleQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SpecialModelName.cs index 1d6445d4d62..7800467822e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SpecialModelName {\n"); sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); sb.Append(" _SpecialModelName: ").Append(_SpecialModelName).Append("\n"); @@ -115,11 +115,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.SpecialPropertyName.GetHashCode(); + hashCode = (hashCode * 59) + this.SpecialPropertyName.GetHashCode(); if (this._SpecialModelName != null) - hashCode = hashCode * 59 + this._SpecialModelName.GetHashCode(); + { + hashCode = (hashCode * 59) + this._SpecialModelName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Tag.cs index 2635acce4e4..3df2c02e2ce 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Tag.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Tag {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -115,11 +115,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TriangleInterface.cs index 14bd3a6724c..7f7abb5bc85 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class TriangleInterface {\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/User.cs index ebd632a90ac..5f2a3020c3d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/User.cs @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); @@ -210,30 +210,52 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Username != null) - hashCode = hashCode * 59 + this.Username.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Username.GetHashCode(); + } if (this.FirstName != null) - hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); + } if (this.LastName != null) - hashCode = hashCode * 59 + this.LastName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.LastName.GetHashCode(); + } if (this.Email != null) - hashCode = hashCode * 59 + this.Email.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Email.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.Phone != null) - hashCode = hashCode * 59 + this.Phone.GetHashCode(); - hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Phone.GetHashCode(); + } + hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); if (this.ObjectWithNoDeclaredProps != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredProps.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); + } if (this.ObjectWithNoDeclaredPropsNullable != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + } if (this.AnyTypeProp != null) - hashCode = hashCode * 59 + this.AnyTypeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); + } if (this.AnyTypePropNullable != null) - hashCode = hashCode * 59 + this.AnyTypePropNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Whale.cs index 57ef3850e97..c30b6dbfabe 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Whale.cs @@ -88,7 +88,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Whale {\n"); sb.Append(" HasBaleen: ").Append(HasBaleen).Append("\n"); sb.Append(" HasTeeth: ").Append(HasTeeth).Append("\n"); @@ -136,12 +136,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.HasBaleen.GetHashCode(); - hashCode = hashCode * 59 + this.HasTeeth.GetHashCode(); + hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); + hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs index bf9735fb37e..4fb60ed8ddf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs @@ -106,7 +106,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -154,11 +154,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Type.GetHashCode(); + hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index ad48306e00c..ac8fbdcdc94 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,21 +237,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/another-fake/dummy", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -279,7 +289,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -293,24 +305,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/another-fake/dummy", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs index 8844aca4ab7..a9e5cfb9c4d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -221,20 +221,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/foo", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -271,23 +279,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/foo", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs index dab406002f8..57a99469634 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -945,20 +945,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/fake/health", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -995,23 +1003,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/health", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1049,21 +1064,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/boolean", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1103,24 +1126,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/boolean", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1158,21 +1188,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/composite", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1212,24 +1250,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/composite", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1267,21 +1312,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/number", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1321,24 +1374,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/number", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1376,21 +1436,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/string", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1430,24 +1498,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/string", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1482,20 +1557,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get>("/fake/array-of-enums", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1532,23 +1615,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/fake/array-of-enums", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1575,7 +1665,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1588,21 +1680,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1631,7 +1731,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1644,24 +1746,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1690,11 +1799,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1707,10 +1820,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; @@ -1718,11 +1837,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-query-params", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1753,11 +1874,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1770,25 +1895,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-query-params", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1816,7 +1948,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1830,21 +1964,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1874,7 +2016,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1888,24 +2032,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1958,11 +2109,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1975,10 +2130,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2034,11 +2195,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2093,11 +2256,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2110,12 +2277,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2170,13 +2342,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2226,10 +2400,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2267,11 +2447,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2323,12 +2505,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2365,13 +2552,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2416,10 +2605,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2446,11 +2641,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2497,12 +2694,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2528,13 +2730,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2561,7 +2765,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2574,21 +2780,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request var localVarResponse = this.Client.Post("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2617,7 +2831,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2630,24 +2846,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2676,11 +2899,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2693,10 +2920,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter @@ -2704,11 +2937,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake/jsonFormData", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2739,11 +2974,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2756,25 +2995,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/jsonFormData", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2809,23 +3055,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2837,10 +3093,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2851,11 +3113,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/test-query-parameters", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2892,23 +3156,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2920,12 +3194,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2935,13 +3214,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/test-query-parameters", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index d4fbb5868ad..c2852b36a44 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,10 +237,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -250,11 +258,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Patch("/fake_classname_test", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -284,7 +294,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -298,12 +310,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -314,13 +331,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake_classname_test", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs index d73282dfca5..39d2e425e63 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs @@ -586,7 +586,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -600,10 +602,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -632,11 +640,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -665,7 +675,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -679,12 +691,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -712,13 +729,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -755,10 +774,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -775,11 +800,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -818,12 +845,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -839,13 +871,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -873,7 +907,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -887,10 +923,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -919,11 +961,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByStatus", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -953,7 +997,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -967,12 +1013,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -1000,13 +1051,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1036,7 +1089,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1050,10 +1105,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1082,11 +1143,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByTags", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1118,7 +1181,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1132,12 +1197,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1165,13 +1235,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1209,10 +1281,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1224,11 +1302,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1268,12 +1348,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1284,13 +1369,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1317,7 +1404,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1420,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1363,11 +1458,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1396,7 +1493,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1410,12 +1509,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1443,13 +1547,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1489,10 +1595,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1513,11 +1625,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1559,12 +1673,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1584,13 +1703,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1632,10 +1753,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1656,11 +1783,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1704,12 +1833,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1729,13 +1863,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1767,7 +1903,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1781,10 +1919,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1802,11 +1946,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1840,7 +1986,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1854,12 +2002,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1876,13 +2029,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs index ad7387db705..7cda385b3b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/StoreApi.cs @@ -345,7 +345,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -357,21 +359,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -400,7 +410,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -412,24 +424,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -464,10 +483,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -478,11 +503,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/store/inventory", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -519,12 +546,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -534,13 +566,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/store/inventory", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -578,21 +612,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -632,24 +674,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -677,7 +726,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -692,21 +743,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request var localVarResponse = this.Client.Post("/store/order", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -736,7 +795,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -751,24 +812,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/store/order", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs index a2f2598c8ac..a1716303f6f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Api/UserApi.cs @@ -517,7 +517,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -530,21 +532,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -573,7 +583,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -586,24 +598,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -630,7 +649,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -643,21 +664,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithArray", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -686,7 +715,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -699,24 +730,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithArray", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -743,7 +781,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -756,21 +796,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithList", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -799,7 +847,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -812,24 +862,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithList", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -856,7 +913,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -868,21 +927,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -911,7 +978,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -923,24 +992,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -968,7 +1044,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -982,21 +1060,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1026,7 +1112,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1040,24 +1128,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1087,11 +1182,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1105,10 +1204,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); @@ -1116,11 +1221,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/user/login", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1152,11 +1259,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1170,25 +1281,32 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/login", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1221,20 +1339,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/user/logout", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1269,23 +1395,30 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/logout", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1314,11 +1447,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1468,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; @@ -1342,11 +1485,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1377,11 +1522,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1394,25 +1543,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 9d6d049ded8..b3ddad35a07 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -117,7 +117,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); @@ -171,23 +171,41 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapProperty != null) - hashCode = hashCode * 59 + this.MapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); + } if (this.MapOfMapProperty != null) - hashCode = hashCode * 59 + this.MapOfMapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); + } if (this.Anytype1 != null) - hashCode = hashCode * 59 + this.Anytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype1 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype2 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype3 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + } if (this.EmptyMap != null) - hashCode = hashCode * 59 + this.EmptyMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesString != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Animal.cs index fd7599d09ca..e8ea00bb46a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Animal.cs @@ -85,7 +85,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Animal {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Color: ").Append(Color).Append("\n"); @@ -133,11 +133,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.Color != null) - hashCode = hashCode * 59 + this.Color.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Color.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ApiResponse.cs index ff7d757270f..79873f4ddfe 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -124,13 +124,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Code.GetHashCode(); + hashCode = (hashCode * 59) + this.Code.GetHashCode(); if (this.Type != null) - hashCode = hashCode * 59 + this.Type.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } if (this.Message != null) - hashCode = hashCode * 59 + this.Message.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Message.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Apple.cs index a702a9ca79f..8b1f87d1aa9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Apple.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Apple {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Origin: ").Append(Origin).Append("\n"); @@ -116,11 +116,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } if (this.Origin != null) - hashCode = hashCode * 59 + this.Origin.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Origin.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AppleReq.cs index 91a8d5c3aeb..1d6d42dc9b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/AppleReq.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AppleReq {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Mealy: ").Append(Mealy).Append("\n"); @@ -117,8 +117,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); - hashCode = hashCode * 59 + this.Mealy.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index e96382b222d..30bf57ef0f5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfArrayOfNumberOnly {\n"); sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 60c5a857656..8a215aad133 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfNumberOnly {\n"); sb.Append(" ArrayNumber: ").Append(ArrayNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayTest.cs index 290926768d2..1a879a1d9ca 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayTest {\n"); sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); @@ -125,13 +125,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayOfString != null) - hashCode = hashCode * 59 + this.ArrayOfString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); + } if (this.ArrayArrayOfInteger != null) - hashCode = hashCode * 59 + this.ArrayArrayOfInteger.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); + } if (this.ArrayArrayOfModel != null) - hashCode = hashCode * 59 + this.ArrayArrayOfModel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Banana.cs index dc0e10d4686..97939597ede 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Banana.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Banana {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BananaReq.cs index ea57bb4f0cc..fdd36929d13 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BananaReq.cs @@ -66,7 +66,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BananaReq {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" Sweet: ").Append(Sweet).Append("\n"); @@ -112,8 +112,8 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); - hashCode = hashCode * 59 + this.Sweet.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BasquePig.cs index f9074c95c04..ea4ff737c89 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/BasquePig.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BasquePig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Capitalization.cs index 3a989f765f9..be68a50a116 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Capitalization.cs @@ -101,7 +101,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Capitalization {\n"); sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); @@ -153,19 +153,33 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SmallCamel != null) - hashCode = hashCode * 59 + this.SmallCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); + } if (this.CapitalCamel != null) - hashCode = hashCode * 59 + this.CapitalCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); + } if (this.SmallSnake != null) - hashCode = hashCode * 59 + this.SmallSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); + } if (this.CapitalSnake != null) - hashCode = hashCode * 59 + this.CapitalSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); + } if (this.SCAETHFlowPoints != null) - hashCode = hashCode * 59 + this.SCAETHFlowPoints.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); + } if (this.ATT_NAME != null) - hashCode = hashCode * 59 + this.ATT_NAME.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Cat.cs index be96bae85eb..2bc55707da9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Cat.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Cat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); @@ -119,9 +119,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -143,7 +145,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/CatAllOf.cs index 8cb5bfc3ef6..3a960e9925e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class CatAllOf {\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Category.cs index 6b0b74ca521..0cc23f5f6c2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Category.cs @@ -80,7 +80,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -127,11 +127,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs index 90545c4d99a..7a15a5297df 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs @@ -92,7 +92,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -141,10 +141,14 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -166,7 +170,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs index b5d479e1742..a353ad7ffd7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCatAllOf.cs @@ -82,7 +82,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCatAllOf {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); @@ -130,10 +130,14 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ClassModel.cs index 80c863484cc..7177e9bf0b6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ClassModel.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ClassModel {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index f3afcc2a734..807f0eb26bf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ComplexQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DanishPig.cs index 59afe7580d0..a27b1db3929 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DanishPig.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DanishPig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DeprecatedObject.cs index bd3d97b081d..1928b236bf6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DeprecatedObject {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Dog.cs index f20af26112c..9cd520deaf8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Dog.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Dog {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); @@ -120,9 +120,13 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -144,7 +148,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DogAllOf.cs index 3588b02b020..7b026acbf1e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DogAllOf {\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs index f7e6702be59..d8cd2a70ef6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); @@ -127,13 +127,21 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.MainShape != null) - hashCode = hashCode * 59 + this.MainShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); + } if (this.ShapeOrNull != null) - hashCode = hashCode * 59 + this.ShapeOrNull.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); + } if (this.NullableShape != null) - hashCode = hashCode * 59 + this.NullableShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); + } if (this.Shapes != null) - hashCode = hashCode * 59 + this.Shapes.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs index f4138fce032..6d7830c0e8b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -109,7 +109,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumArrays {\n"); sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); sb.Append(" ArrayEnum: ").Append(ArrayEnum).Append("\n"); @@ -156,10 +156,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustSymbol.GetHashCode(); - hashCode = hashCode * 59 + this.ArrayEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumTest.cs index 178d540314d..6f3d2272c5c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EnumTest.cs @@ -238,7 +238,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); @@ -292,17 +292,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.EnumString.GetHashCode(); - hashCode = hashCode * 59 + this.EnumStringRequired.GetHashCode(); - hashCode = hashCode * 59 + this.EnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.EnumIntegerOnly.GetHashCode(); - hashCode = hashCode * 59 + this.EnumNumber.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnum.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumDefaultValue.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumIntegerDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumStringRequired.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 2e8e4d0c17d..a931c0d6327 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EquilateralTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/File.cs index 1e859462b14..e77d15e06bc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/File.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class File {\n"); sb.Append(" SourceURI: ").Append(SourceURI).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SourceURI != null) - hashCode = hashCode * 59 + this.SourceURI.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index b996e287ea7..6808978c49f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FileSchemaTestClass {\n"); sb.Append(" File: ").Append(File).Append("\n"); sb.Append(" Files: ").Append(Files).Append("\n"); @@ -116,11 +116,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); + { + hashCode = (hashCode * 59) + this.File.GetHashCode(); + } if (this.Files != null) - hashCode = hashCode * 59 + this.Files.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Files.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Foo.cs index a5aabbae4f3..e64aac7b631 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Foo.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Foo {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FormatTest.cs index ef60b6bb9fe..eb38d586bbb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/FormatTest.cs @@ -199,7 +199,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); @@ -260,33 +260,53 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Integer.GetHashCode(); - hashCode = hashCode * 59 + this.Int32.GetHashCode(); - hashCode = hashCode * 59 + this.Int64.GetHashCode(); - hashCode = hashCode * 59 + this.Number.GetHashCode(); - hashCode = hashCode * 59 + this.Float.GetHashCode(); - hashCode = hashCode * 59 + this.Double.GetHashCode(); - hashCode = hashCode * 59 + this.Decimal.GetHashCode(); + hashCode = (hashCode * 59) + this.Integer.GetHashCode(); + hashCode = (hashCode * 59) + this.Int32.GetHashCode(); + hashCode = (hashCode * 59) + this.Int64.GetHashCode(); + hashCode = (hashCode * 59) + this.Number.GetHashCode(); + hashCode = (hashCode * 59) + this.Float.GetHashCode(); + hashCode = (hashCode * 59) + this.Double.GetHashCode(); + hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.Byte != null) - hashCode = hashCode * 59 + this.Byte.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Byte.GetHashCode(); + } if (this.Binary != null) - hashCode = hashCode * 59 + this.Binary.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Binary.GetHashCode(); + } if (this.Date != null) - hashCode = hashCode * 59 + this.Date.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Date.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.PatternWithDigits != null) - hashCode = hashCode * 59 + this.PatternWithDigits.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); + } if (this.PatternWithDigitsAndDelimiter != null) - hashCode = hashCode * 59 + this.PatternWithDigitsAndDelimiter.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -299,61 +319,61 @@ namespace Org.OpenAPITools.Model public IEnumerable Validate(ValidationContext validationContext) { // Integer (int) maximum - if(this.Integer > (int)100) + if (this.Integer > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if(this.Integer < (int)10) + if (this.Integer < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } // Int32 (int) maximum - if(this.Int32 > (int)200) + if (this.Int32 > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if(this.Int32 < (int)20) + if (this.Int32 < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Number (decimal) maximum - if(this.Number > (decimal)543.2) + if (this.Number > (decimal)543.2) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); } // Number (decimal) minimum - if(this.Number < (decimal)32.1) + if (this.Number < (decimal)32.1) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); } // Float (float) maximum - if(this.Float > (float)987.6) + if (this.Float > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); } // Float (float) minimum - if(this.Float < (float)54.3) + if (this.Float < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); } // Double (double) maximum - if(this.Double > (double)123.4) + if (this.Double > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); } // Double (double) minimum - if(this.Double < (double)67.8) + if (this.Double < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); } @@ -366,13 +386,13 @@ namespace Org.OpenAPITools.Model } // Password (string) maxLength - if(this.Password != null && this.Password.Length > 64) + if (this.Password != null && this.Password.Length > 64) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); } // Password (string) minLength - if(this.Password != null && this.Password.Length < 10) + if (this.Password != null && this.Password.Length < 10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 9edacb3815a..cee75f3f815 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class GrandparentAnimal {\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -123,9 +123,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.PetType != null) - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index f6219182b29..52099a7095e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -81,7 +81,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HasOnlyReadOnly {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Foo: ").Append(Foo).Append("\n"); @@ -129,11 +129,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Foo != null) - hashCode = hashCode * 59 + this.Foo.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Foo.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HealthCheckResult.cs index c7c342d258a..e8cbb68e2e4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HealthCheckResult {\n"); sb.Append(" NullableMessage: ").Append(NullableMessage).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.NullableMessage != null) - hashCode = hashCode * 59 + this.NullableMessage.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs index e492ade1fc6..ae46f1f0098 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/InlineResponseDefault.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponseDefault {\n"); sb.Append(" String: ").Append(String).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 8d02354be3f..50e7ce4aaa8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class IsoscelesTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/List.cs index 5f3483a6e30..00814d11069 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/List.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class List {\n"); sb.Append(" _123List: ").Append(_123List).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._123List != null) - hashCode = hashCode * 59 + this._123List.GetHashCode(); + { + hashCode = (hashCode * 59) + this._123List.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs index fa93bf24ec0..8b5a73e7736 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MapTest.cs @@ -105,7 +105,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MapTest {\n"); sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); @@ -155,14 +155,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapMapOfString != null) - hashCode = hashCode * 59 + this.MapMapOfString.GetHashCode(); - hashCode = hashCode * 59 + this.MapOfEnumString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); if (this.DirectMap != null) - hashCode = hashCode * 59 + this.DirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); + } if (this.IndirectMap != null) - hashCode = hashCode * 59 + this.IndirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 8853f837f9e..3225727af37 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); @@ -125,13 +125,21 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Map != null) - hashCode = hashCode * 59 + this.Map.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Map.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Model200Response.cs index 629a1fde7fb..79a49ef91d2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Model200Response.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Model200Response {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); @@ -115,11 +115,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = (hashCode * 59) + this.Name.GetHashCode(); if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ModelClient.cs index e28bc67d630..1995ec4b169 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ModelClient.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ModelClient {\n"); sb.Append(" _Client: ").Append(_Client).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -107,9 +107,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._Client != null) - hashCode = hashCode * 59 + this._Client.GetHashCode(); + { + hashCode = (hashCode * 59) + this._Client.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs index 462b3458215..0dc21bb656f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Name.cs @@ -104,7 +104,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" _Name: ").Append(_Name).Append("\n"); sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); @@ -153,13 +153,17 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Name.GetHashCode(); - hashCode = hashCode * 59 + this.SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + this._Name.GetHashCode(); + hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); if (this.Property != null) - hashCode = hashCode * 59 + this.Property.GetHashCode(); - hashCode = hashCode * 59 + this._123Number.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Property.GetHashCode(); + } + hashCode = (hashCode * 59) + this._123Number.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs index 3a34e8cc128..57555c37678 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs @@ -142,7 +142,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); @@ -200,29 +200,53 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.IntegerProp != null) - hashCode = hashCode * 59 + this.IntegerProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); + } if (this.NumberProp != null) - hashCode = hashCode * 59 + this.NumberProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); + } if (this.BooleanProp != null) - hashCode = hashCode * 59 + this.BooleanProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); + } if (this.StringProp != null) - hashCode = hashCode * 59 + this.StringProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); + } if (this.DateProp != null) - hashCode = hashCode * 59 + this.DateProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); + } if (this.DatetimeProp != null) - hashCode = hashCode * 59 + this.DatetimeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); + } if (this.ArrayNullableProp != null) - hashCode = hashCode * 59 + this.ArrayNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); + } if (this.ArrayAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ArrayAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); + } if (this.ArrayItemsNullable != null) - hashCode = hashCode * 59 + this.ArrayItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); + } if (this.ObjectNullableProp != null) - hashCode = hashCode * 59 + this.ObjectNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); + } if (this.ObjectAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ObjectAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); + } if (this.ObjectItemsNullable != null) - hashCode = hashCode * 59 + this.ObjectItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NumberOnly.cs index 34abb32eabd..97f869b0ebc 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NumberOnly {\n"); sb.Append(" JustNumber: ").Append(JustNumber).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.JustNumber.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 021bfe71e02..86ea32998f8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -87,7 +87,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ObjectWithDeprecatedFields {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); @@ -137,14 +137,22 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); - hashCode = hashCode * 59 + this.Id.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.DeprecatedRef != null) - hashCode = hashCode * 59 + this.DeprecatedRef.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); + } if (this.Bars != null) - hashCode = hashCode * 59 + this.Bars.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bars.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Order.cs index e1abd07a05c..5c52482e79b 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Order.cs @@ -128,7 +128,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); @@ -179,15 +179,19 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); - hashCode = hashCode * 59 + this.PetId.GetHashCode(); - hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.PetId.GetHashCode(); + hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); if (this.ShipDate != null) - hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); - hashCode = hashCode * 59 + this.Complete.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + hashCode = (hashCode * 59) + this.Complete.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/OuterComposite.cs index 88449a1c843..3209f6d6244 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -76,7 +76,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class OuterComposite {\n"); sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); sb.Append(" MyString: ").Append(MyString).Append("\n"); @@ -124,12 +124,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.MyNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.MyNumber.GetHashCode(); if (this.MyString != null) - hashCode = hashCode * 59 + this.MyString.GetHashCode(); - hashCode = hashCode * 59 + this.MyBoolean.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MyString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ParentPet.cs index 899984fcc5b..ac986b555ef 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ParentPet.cs @@ -64,7 +64,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ParentPet {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -111,7 +111,9 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } @@ -133,7 +135,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pet.cs index 8b3b614493f..31fd118f4f6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Pet.cs @@ -144,7 +144,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Category: ").Append(Category).Append("\n"); @@ -195,18 +195,28 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Category != null) - hashCode = hashCode * 59 + this.Category.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Category.GetHashCode(); + } if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.PhotoUrls != null) - hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); + } if (this.Tags != null) - hashCode = hashCode * 59 + this.Tags.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Tags.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index de200d38d54..4d7c39c4364 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class QuadrilateralInterface {\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 08a294a2290..ad59ca83286 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ReadOnlyFirst {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Baz: ").Append(Baz).Append("\n"); @@ -122,11 +122,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Baz != null) - hashCode = hashCode * 59 + this.Baz.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Baz.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Return.cs index 74317fbbfec..e702e015703 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Return.cs @@ -60,7 +60,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Return {\n"); sb.Append(" _Return: ").Append(_Return).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -106,9 +106,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Return.GetHashCode(); + hashCode = (hashCode * 59) + this._Return.GetHashCode(); if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 6b4869ce839..23683947147 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ScaleneTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeInterface.cs index ccd305b4509..92774561aaa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ShapeInterface {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index d698a788f8e..fc9b37ce01f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -84,7 +84,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SimpleQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -132,11 +132,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SpecialModelName.cs index 1d6445d4d62..7800467822e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SpecialModelName {\n"); sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); sb.Append(" _SpecialModelName: ").Append(_SpecialModelName).Append("\n"); @@ -115,11 +115,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.SpecialPropertyName.GetHashCode(); + hashCode = (hashCode * 59) + this.SpecialPropertyName.GetHashCode(); if (this._SpecialModelName != null) - hashCode = hashCode * 59 + this._SpecialModelName.GetHashCode(); + { + hashCode = (hashCode * 59) + this._SpecialModelName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Tag.cs index 2635acce4e4..3df2c02e2ce 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Tag.cs @@ -68,7 +68,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Tag {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -115,11 +115,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/TriangleInterface.cs index 14bd3a6724c..7f7abb5bc85 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -72,7 +72,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class TriangleInterface {\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -119,9 +119,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/User.cs index ebd632a90ac..5f2a3020c3d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/User.cs @@ -153,7 +153,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); @@ -210,30 +210,52 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Username != null) - hashCode = hashCode * 59 + this.Username.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Username.GetHashCode(); + } if (this.FirstName != null) - hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); + } if (this.LastName != null) - hashCode = hashCode * 59 + this.LastName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.LastName.GetHashCode(); + } if (this.Email != null) - hashCode = hashCode * 59 + this.Email.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Email.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.Phone != null) - hashCode = hashCode * 59 + this.Phone.GetHashCode(); - hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Phone.GetHashCode(); + } + hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); if (this.ObjectWithNoDeclaredProps != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredProps.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); + } if (this.ObjectWithNoDeclaredPropsNullable != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + } if (this.AnyTypeProp != null) - hashCode = hashCode * 59 + this.AnyTypeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); + } if (this.AnyTypePropNullable != null) - hashCode = hashCode * 59 + this.AnyTypePropNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Whale.cs index 57ef3850e97..c30b6dbfabe 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Whale.cs @@ -88,7 +88,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Whale {\n"); sb.Append(" HasBaleen: ").Append(HasBaleen).Append("\n"); sb.Append(" HasTeeth: ").Append(HasTeeth).Append("\n"); @@ -136,12 +136,16 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.HasBaleen.GetHashCode(); - hashCode = hashCode * 59 + this.HasTeeth.GetHashCode(); + hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); + hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs index bf9735fb37e..4fb60ed8ddf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs @@ -106,7 +106,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -154,11 +154,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Type.GetHashCode(); + hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs index ad48306e00c..ac8fbdcdc94 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/AnotherFakeApi.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,21 +237,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/another-fake/dummy", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -279,7 +289,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling AnotherFakeApi->Call123TestSpecialTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -293,24 +305,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/another-fake/dummy", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("Call123TestSpecialTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs index 8844aca4ab7..a9e5cfb9c4d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -221,20 +221,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/foo", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -271,23 +279,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/foo", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FooGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs index dab406002f8..57a99469634 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs @@ -945,20 +945,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/fake/health", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -995,23 +1003,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/health", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeHealthGet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1049,21 +1064,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/boolean", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1103,24 +1126,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/boolean", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterBooleanSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1158,21 +1188,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/composite", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1212,24 +1250,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = outerComposite; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/composite", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterCompositeSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1267,21 +1312,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/number", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1321,24 +1374,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/number", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterNumberSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1376,21 +1436,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request var localVarResponse = this.Client.Post("/fake/outer/string", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1430,24 +1498,31 @@ namespace Org.OpenAPITools.Api "*/*" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = body; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/outer/string", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FakeOuterStringSerialize", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1482,20 +1557,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get>("/fake/array-of-enums", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1532,23 +1615,30 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/fake/array-of-enums", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetArrayOfEnums", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1575,7 +1665,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1588,21 +1680,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1631,7 +1731,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'fileSchemaTestClass' is set if (fileSchemaTestClass == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'fileSchemaTestClass' when calling FakeApi->TestBodyWithFileSchema"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1644,24 +1746,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = fileSchemaTestClass; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-file-schema", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithFileSchema", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1690,11 +1799,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1707,10 +1820,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; @@ -1718,11 +1837,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/body-with-query-params", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1753,11 +1874,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'query' is set if (query == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'query' when calling FakeApi->TestBodyWithQueryParams"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling FakeApi->TestBodyWithQueryParams"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1770,25 +1895,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "query", query)); localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/body-with-query-params", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestBodyWithQueryParams", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1816,7 +1948,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1830,21 +1964,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request var localVarResponse = this.Client.Patch("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1874,7 +2016,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeApi->TestClientModel"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1888,24 +2032,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClientModel", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1958,11 +2109,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1975,10 +2130,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2034,11 +2195,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2093,11 +2256,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'patternWithoutDelimiter' when calling FakeApi->TestEndpointParameters"); + } // verify the required parameter '_byte' is set if (_byte == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter '_byte' when calling FakeApi->TestEndpointParameters"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2110,12 +2277,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (integer != null) { @@ -2170,13 +2342,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEndpointParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2226,10 +2400,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2267,11 +2447,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2323,12 +2505,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } if (enumQueryStringArray != null) { @@ -2365,13 +2552,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestEnumParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2416,10 +2605,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2446,11 +2641,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/fake", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2497,12 +2694,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_string_group", requiredStringGroup)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "required_int64_group", requiredInt64Group)); @@ -2528,13 +2730,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/fake", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestGroupParameters", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2561,7 +2765,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2574,21 +2780,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request var localVarResponse = this.Client.Post("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2617,7 +2831,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requestBody' is set if (requestBody == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestInlineAdditionalProperties"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2630,24 +2846,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = requestBody; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/inline-additionalProperties", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestInlineAdditionalProperties", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2676,11 +2899,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2693,10 +2920,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter @@ -2704,11 +2937,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/fake/jsonFormData", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2739,11 +2974,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'param' is set if (param == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param' when calling FakeApi->TestJsonFormData"); + } // verify the required parameter 'param2' is set if (param2 == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'param2' when calling FakeApi->TestJsonFormData"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2756,25 +2995,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.FormParameters.Add("param", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param)); // form parameter localVarRequestOptions.FormParameters.Add("param2", Org.OpenAPITools.Client.ClientUtils.ParameterToString(param2)); // form parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/fake/jsonFormData", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestJsonFormData", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2809,23 +3055,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2837,10 +3093,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2851,11 +3113,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/fake/test-query-parameters", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -2892,23 +3156,33 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pipe' is set if (pipe == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pipe' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'ioutil' is set if (ioutil == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'ioutil' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'http' is set if (http == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'http' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'url' is set if (url == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'url' when calling FakeApi->TestQueryParameterCollectionFormat"); + } // verify the required parameter 'context' is set if (context == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'context' when calling FakeApi->TestQueryParameterCollectionFormat"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -2920,12 +3194,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("multi", "pipe", pipe)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "ioutil", ioutil)); @@ -2935,13 +3214,15 @@ namespace Org.OpenAPITools.Api // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/fake/test-query-parameters", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestQueryParameterCollectionFormat", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index d4fbb5868ad..c2852b36a44 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -221,7 +221,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -235,10 +237,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -250,11 +258,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Patch("/fake_classname_test", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -284,7 +294,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'modelClient' is set if (modelClient == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'modelClient' when calling FakeClassnameTags123Api->TestClassname"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -298,12 +310,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = modelClient; @@ -314,13 +331,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PatchAsync("/fake_classname_test", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("TestClassname", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs index d73282dfca5..39d2e425e63 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs @@ -586,7 +586,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -600,10 +602,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -632,11 +640,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -665,7 +675,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -679,12 +691,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -712,13 +729,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -755,10 +774,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -775,11 +800,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -818,12 +845,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -839,13 +871,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -873,7 +907,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -887,10 +923,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -919,11 +961,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByStatus", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -953,7 +997,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -967,12 +1013,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -1000,13 +1051,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1036,7 +1089,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1050,10 +1105,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1082,11 +1143,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByTags", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1118,7 +1181,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1132,12 +1197,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1165,13 +1235,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1209,10 +1281,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1224,11 +1302,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1268,12 +1348,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1284,13 +1369,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1317,7 +1404,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1420,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1363,11 +1458,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1396,7 +1493,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1410,12 +1509,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1443,13 +1547,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1489,10 +1595,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1513,11 +1625,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1559,12 +1673,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1584,13 +1703,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1632,10 +1753,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1656,11 +1783,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1704,12 +1833,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1729,13 +1863,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1767,7 +1903,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1781,10 +1919,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1802,11 +1946,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1840,7 +1986,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'requiredFile' is set if (requiredFile == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requiredFile' when calling PetApi->UploadFileWithRequiredFile"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1854,12 +2002,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1876,13 +2029,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/{petId}/uploadImageWithRequiredFile", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFileWithRequiredFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs index ad7387db705..7cda385b3b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/StoreApi.cs @@ -345,7 +345,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -357,21 +359,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -400,7 +410,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -412,24 +424,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -464,10 +483,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -478,11 +503,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/store/inventory", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -519,12 +546,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -534,13 +566,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/store/inventory", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -578,21 +612,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/store/order/{order_id}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -632,24 +674,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("order_id", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/store/order/{order_id}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -677,7 +726,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -692,21 +743,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request var localVarResponse = this.Client.Post("/store/order", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -736,7 +795,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -751,24 +812,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/store/order", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs index a2f2598c8ac..a1716303f6f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Api/UserApi.cs @@ -517,7 +517,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -530,21 +532,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -573,7 +583,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -586,24 +598,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -630,7 +649,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -643,21 +664,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithArray", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -686,7 +715,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -699,24 +730,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithArray", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -743,7 +781,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -756,21 +796,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithList", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -799,7 +847,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -812,24 +862,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithList", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -856,7 +913,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -868,21 +927,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -911,7 +978,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -923,24 +992,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -968,7 +1044,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -982,21 +1060,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1026,7 +1112,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1040,24 +1128,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1087,11 +1182,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1105,10 +1204,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); @@ -1116,11 +1221,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/user/login", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1152,11 +1259,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1170,25 +1281,32 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/login", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1221,20 +1339,28 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request var localVarResponse = this.Client.Get("/user/logout", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1269,23 +1395,30 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/logout", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1314,11 +1447,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1331,10 +1468,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; @@ -1342,11 +1485,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1377,11 +1522,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1394,25 +1543,32 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index e58bad81ffe..d7f64e083d9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -110,7 +110,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); @@ -163,21 +163,37 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapProperty != null) - hashCode = hashCode * 59 + this.MapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapProperty.GetHashCode(); + } if (this.MapOfMapProperty != null) - hashCode = hashCode * 59 + this.MapOfMapProperty.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapOfMapProperty.GetHashCode(); + } if (this.Anytype1 != null) - hashCode = hashCode * 59 + this.Anytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Anytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype1 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype1.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype2 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype2.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesAnytype3 != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesAnytype3.GetHashCode(); + } if (this.EmptyMap != null) - hashCode = hashCode * 59 + this.EmptyMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.EmptyMap.GetHashCode(); + } if (this.MapWithUndeclaredPropertiesString != null) - hashCode = hashCode * 59 + this.MapWithUndeclaredPropertiesString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapWithUndeclaredPropertiesString.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Animal.cs index 633d513a1e1..c86eb126fa7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Animal.cs @@ -75,7 +75,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Animal {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Color: ").Append(Color).Append("\n"); @@ -122,9 +122,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.Color != null) - hashCode = hashCode * 59 + this.Color.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Color.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ApiResponse.cs index 7f1235eec65..b29884509c0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -116,11 +116,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Code.GetHashCode(); + hashCode = (hashCode * 59) + this.Code.GetHashCode(); if (this.Type != null) - hashCode = hashCode * 59 + this.Type.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } if (this.Message != null) - hashCode = hashCode * 59 + this.Message.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Message.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Apple.cs index 43fcc0a835e..4706c3f55e8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Apple.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Apple {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Origin: ").Append(Origin).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } if (this.Origin != null) - hashCode = hashCode * 59 + this.Origin.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Origin.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AppleReq.cs index 91a8d5c3aeb..1d6d42dc9b3 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/AppleReq.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class AppleReq {\n"); sb.Append(" Cultivar: ").Append(Cultivar).Append("\n"); sb.Append(" Mealy: ").Append(Mealy).Append("\n"); @@ -117,8 +117,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Cultivar != null) - hashCode = hashCode * 59 + this.Cultivar.GetHashCode(); - hashCode = hashCode * 59 + this.Mealy.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Cultivar.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Mealy.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index 0a6725d5956..7bb75ee4dd7 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfArrayOfNumberOnly {\n"); sb.Append(" ArrayArrayNumber: ").Append(ArrayArrayNumber).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayNumber.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index d332306ed70..1ea6f5248b2 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayOfNumberOnly {\n"); sb.Append(" ArrayNumber: ").Append(ArrayNumber).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayNumber != null) - hashCode = hashCode * 59 + this.ArrayNumber.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNumber.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayTest.cs index 1f157ececd9..9564cd48483 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ArrayTest {\n"); sb.Append(" ArrayOfString: ").Append(ArrayOfString).Append("\n"); sb.Append(" ArrayArrayOfInteger: ").Append(ArrayArrayOfInteger).Append("\n"); @@ -117,11 +117,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ArrayOfString != null) - hashCode = hashCode * 59 + this.ArrayOfString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayOfString.GetHashCode(); + } if (this.ArrayArrayOfInteger != null) - hashCode = hashCode * 59 + this.ArrayArrayOfInteger.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfInteger.GetHashCode(); + } if (this.ArrayArrayOfModel != null) - hashCode = hashCode * 59 + this.ArrayArrayOfModel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayArrayOfModel.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Banana.cs index 8f20422800b..d0053dbae2d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Banana.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Banana {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append("}\n"); @@ -98,7 +98,7 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BananaReq.cs index ea57bb4f0cc..fdd36929d13 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BananaReq.cs @@ -66,7 +66,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BananaReq {\n"); sb.Append(" LengthCm: ").Append(LengthCm).Append("\n"); sb.Append(" Sweet: ").Append(Sweet).Append("\n"); @@ -112,8 +112,8 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.LengthCm.GetHashCode(); - hashCode = hashCode * 59 + this.Sweet.GetHashCode(); + hashCode = (hashCode * 59) + this.LengthCm.GetHashCode(); + hashCode = (hashCode * 59) + this.Sweet.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BasquePig.cs index 2cc42f67f5a..58c8bebce5e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/BasquePig.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class BasquePig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append("}\n"); @@ -108,7 +108,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Capitalization.cs index 486f269d439..2f53c995da9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Capitalization.cs @@ -94,7 +94,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Capitalization {\n"); sb.Append(" SmallCamel: ").Append(SmallCamel).Append("\n"); sb.Append(" CapitalCamel: ").Append(CapitalCamel).Append("\n"); @@ -145,17 +145,29 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SmallCamel != null) - hashCode = hashCode * 59 + this.SmallCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallCamel.GetHashCode(); + } if (this.CapitalCamel != null) - hashCode = hashCode * 59 + this.CapitalCamel.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalCamel.GetHashCode(); + } if (this.SmallSnake != null) - hashCode = hashCode * 59 + this.SmallSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SmallSnake.GetHashCode(); + } if (this.CapitalSnake != null) - hashCode = hashCode * 59 + this.CapitalSnake.GetHashCode(); + { + hashCode = (hashCode * 59) + this.CapitalSnake.GetHashCode(); + } if (this.SCAETHFlowPoints != null) - hashCode = hashCode * 59 + this.SCAETHFlowPoints.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SCAETHFlowPoints.GetHashCode(); + } if (this.ATT_NAME != null) - hashCode = hashCode * 59 + this.ATT_NAME.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ATT_NAME.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Cat.cs index 62a650fa576..87e09bc6a57 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Cat.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Cat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); @@ -108,7 +108,7 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); return hashCode; } } @@ -130,7 +130,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/CatAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/CatAllOf.cs index bc9abc8a0c4..607c2c650ed 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/CatAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/CatAllOf.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class CatAllOf {\n"); sb.Append(" Declawed: ").Append(Declawed).Append("\n"); sb.Append("}\n"); @@ -98,7 +98,7 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Declawed.GetHashCode(); + hashCode = (hashCode * 59) + this.Declawed.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Category.cs index 92c01063269..fb7778939b4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Category.cs @@ -70,7 +70,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -116,9 +116,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } return hashCode; } } 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 78880b84b1e..d2b81927885 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 @@ -82,7 +82,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCat {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -130,8 +130,10 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); return hashCode; } } @@ -153,7 +155,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } 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 28293972beb..58d2cec42cc 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 @@ -75,7 +75,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ChildCatAllOf {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); @@ -122,8 +122,10 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + 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/ClassModel.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ClassModel.cs index bdd2c06b7f3..5ead2b7fbfa 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ClassModel.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ClassModel {\n"); sb.Append(" Class: ").Append(Class).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index e2c4a41d548..ea5a8782d2a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ComplexQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DanishPig.cs index 0f83345da89..1718d7d4339 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DanishPig.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DanishPig {\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append("}\n"); @@ -108,7 +108,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DeprecatedObject.cs index 82df9376363..2c3722a6b4a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DeprecatedObject {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Dog.cs index 1b57dbff541..b49df98acbf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Dog.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Dog {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); @@ -109,7 +109,9 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } return hashCode; } } @@ -131,7 +133,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DogAllOf.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DogAllOf.cs index d885628e2e9..036f993e64a 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DogAllOf.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/DogAllOf.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class DogAllOf {\n"); sb.Append(" Breed: ").Append(Breed).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Breed != null) - hashCode = hashCode * 59 + this.Breed.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Breed.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs index f7e6702be59..d8cd2a70ef6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs @@ -77,7 +77,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); @@ -127,13 +127,21 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.MainShape != null) - hashCode = hashCode * 59 + this.MainShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); + } if (this.ShapeOrNull != null) - hashCode = hashCode * 59 + this.ShapeOrNull.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeOrNull.GetHashCode(); + } if (this.NullableShape != null) - hashCode = hashCode * 59 + this.NullableShape.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableShape.GetHashCode(); + } if (this.Shapes != null) - hashCode = hashCode * 59 + this.Shapes.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Shapes.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumArrays.cs index 05ac48397ed..89584f4501e 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -102,7 +102,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumArrays {\n"); sb.Append(" JustSymbol: ").Append(JustSymbol).Append("\n"); sb.Append(" ArrayEnum: ").Append(ArrayEnum).Append("\n"); @@ -148,8 +148,8 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustSymbol.GetHashCode(); - hashCode = hashCode * 59 + this.ArrayEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.JustSymbol.GetHashCode(); + hashCode = (hashCode * 59) + this.ArrayEnum.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumTest.cs index dcaaac95507..54937a2fbf6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EnumTest.cs @@ -228,7 +228,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); @@ -281,15 +281,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.EnumString.GetHashCode(); - hashCode = hashCode * 59 + this.EnumStringRequired.GetHashCode(); - hashCode = hashCode * 59 + this.EnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.EnumIntegerOnly.GetHashCode(); - hashCode = hashCode * 59 + this.EnumNumber.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnum.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumInteger.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumDefaultValue.GetHashCode(); - hashCode = hashCode * 59 + this.OuterEnumIntegerDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumStringRequired.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.EnumNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnum.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.OuterEnumIntegerDefaultValue.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 342848daed0..48f12495bbf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class EquilateralTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/File.cs index 553899ee748..7010f9a6103 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/File.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class File {\n"); sb.Append(" SourceURI: ").Append(SourceURI).Append("\n"); sb.Append("}\n"); @@ -100,7 +100,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.SourceURI != null) - hashCode = hashCode * 59 + this.SourceURI.GetHashCode(); + { + hashCode = (hashCode * 59) + this.SourceURI.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index b799b6685c3..077da6361a9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FileSchemaTestClass {\n"); sb.Append(" File: ").Append(File).Append("\n"); sb.Append(" Files: ").Append(Files).Append("\n"); @@ -108,9 +108,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.File != null) - hashCode = hashCode * 59 + this.File.GetHashCode(); + { + hashCode = (hashCode * 59) + this.File.GetHashCode(); + } if (this.Files != null) - hashCode = hashCode * 59 + this.Files.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Files.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Foo.cs index 3203319075a..3abdc1cb6a0 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Foo.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Foo {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append("}\n"); @@ -100,7 +100,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs index 956e398caf3..586cdcb33db 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs @@ -189,7 +189,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); sb.Append(" Int32: ").Append(Int32).Append("\n"); @@ -249,31 +249,49 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Integer.GetHashCode(); - hashCode = hashCode * 59 + this.Int32.GetHashCode(); - hashCode = hashCode * 59 + this.Int64.GetHashCode(); - hashCode = hashCode * 59 + this.Number.GetHashCode(); - hashCode = hashCode * 59 + this.Float.GetHashCode(); - hashCode = hashCode * 59 + this.Double.GetHashCode(); - hashCode = hashCode * 59 + this.Decimal.GetHashCode(); + hashCode = (hashCode * 59) + this.Integer.GetHashCode(); + hashCode = (hashCode * 59) + this.Int32.GetHashCode(); + hashCode = (hashCode * 59) + this.Int64.GetHashCode(); + hashCode = (hashCode * 59) + this.Number.GetHashCode(); + hashCode = (hashCode * 59) + this.Float.GetHashCode(); + hashCode = (hashCode * 59) + this.Double.GetHashCode(); + hashCode = (hashCode * 59) + this.Decimal.GetHashCode(); if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } if (this.Byte != null) - hashCode = hashCode * 59 + this.Byte.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Byte.GetHashCode(); + } if (this.Binary != null) - hashCode = hashCode * 59 + this.Binary.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Binary.GetHashCode(); + } if (this.Date != null) - hashCode = hashCode * 59 + this.Date.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Date.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.PatternWithDigits != null) - hashCode = hashCode * 59 + this.PatternWithDigits.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigits.GetHashCode(); + } if (this.PatternWithDigitsAndDelimiter != null) - hashCode = hashCode * 59 + this.PatternWithDigitsAndDelimiter.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PatternWithDigitsAndDelimiter.GetHashCode(); + } return hashCode; } } @@ -286,61 +304,61 @@ namespace Org.OpenAPITools.Model public IEnumerable Validate(ValidationContext validationContext) { // Integer (int) maximum - if(this.Integer > (int)100) + if (this.Integer > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if(this.Integer < (int)10) + if (this.Integer < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } // Int32 (int) maximum - if(this.Int32 > (int)200) + if (this.Int32 > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if(this.Int32 < (int)20) + if (this.Int32 < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Number (decimal) maximum - if(this.Number > (decimal)543.2) + if (this.Number > (decimal)543.2) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); } // Number (decimal) minimum - if(this.Number < (decimal)32.1) + if (this.Number < (decimal)32.1) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); } // Float (float) maximum - if(this.Float > (float)987.6) + if (this.Float > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value less than or equal to 987.6.", new [] { "Float" }); } // Float (float) minimum - if(this.Float < (float)54.3) + if (this.Float < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Float, must be a value greater than or equal to 54.3.", new [] { "Float" }); } // Double (double) maximum - if(this.Double > (double)123.4) + if (this.Double > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value less than or equal to 123.4.", new [] { "Double" }); } // Double (double) minimum - if(this.Double < (double)67.8) + if (this.Double < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Double, must be a value greater than or equal to 67.8.", new [] { "Double" }); } @@ -353,13 +371,13 @@ namespace Org.OpenAPITools.Model } // Password (string) maxLength - if(this.Password != null && this.Password.Length > 64) + if (this.Password != null && this.Password.Length > 64) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); } // Password (string) minLength - if(this.Password != null && this.Password.Length < 10) + if (this.Password != null && this.Password.Length < 10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 81a69e9da4b..579beb9a18d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -66,7 +66,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class GrandparentAnimal {\n"); sb.Append(" PetType: ").Append(PetType).Append("\n"); sb.Append("}\n"); @@ -112,7 +112,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.PetType != null) - hashCode = hashCode * 59 + this.PetType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PetType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 79ae107761a..498c8226fc1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HasOnlyReadOnly {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Foo: ").Append(Foo).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Foo != null) - hashCode = hashCode * 59 + this.Foo.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Foo.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HealthCheckResult.cs index 06ccf424c78..520aa05bac4 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class HealthCheckResult {\n"); sb.Append(" NullableMessage: ").Append(NullableMessage).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.NullableMessage != null) - hashCode = hashCode * 59 + this.NullableMessage.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NullableMessage.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineResponseDefault.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineResponseDefault.cs index 8b38704524b..755f9aebc70 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineResponseDefault.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/InlineResponseDefault.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class InlineResponseDefault {\n"); sb.Append(" String: ").Append(String).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.String != null) - hashCode = hashCode * 59 + this.String.GetHashCode(); + { + hashCode = (hashCode * 59) + this.String.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 8d02354be3f..50e7ce4aaa8 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class IsoscelesTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/List.cs index a3e18100b37..33b69997a74 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/List.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class List {\n"); sb.Append(" _123List: ").Append(_123List).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._123List != null) - hashCode = hashCode * 59 + this._123List.GetHashCode(); + { + hashCode = (hashCode * 59) + this._123List.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MapTest.cs index 7265530086e..d947debc81c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MapTest.cs @@ -98,7 +98,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MapTest {\n"); sb.Append(" MapMapOfString: ").Append(MapMapOfString).Append("\n"); sb.Append(" MapOfEnumString: ").Append(MapOfEnumString).Append("\n"); @@ -147,12 +147,18 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.MapMapOfString != null) - hashCode = hashCode * 59 + this.MapMapOfString.GetHashCode(); - hashCode = hashCode * 59 + this.MapOfEnumString.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MapMapOfString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MapOfEnumString.GetHashCode(); if (this.DirectMap != null) - hashCode = hashCode * 59 + this.DirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DirectMap.GetHashCode(); + } if (this.IndirectMap != null) - hashCode = hashCode * 59 + this.IndirectMap.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IndirectMap.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index ff7fa7cfa9e..44fc73ca3a9 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); @@ -117,11 +117,17 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } if (this.DateTime != null) - hashCode = hashCode * 59 + this.DateTime.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateTime.GetHashCode(); + } if (this.Map != null) - hashCode = hashCode * 59 + this.Map.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Map.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Model200Response.cs index 94512afac2d..938ffce9d00 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Model200Response.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Model200Response {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Class: ").Append(Class).Append("\n"); @@ -107,9 +107,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Name.GetHashCode(); + hashCode = (hashCode * 59) + this.Name.GetHashCode(); if (this.Class != null) - hashCode = hashCode * 59 + this.Class.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Class.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ModelClient.cs index 32ed922e390..a6746a6136c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ModelClient.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ModelClient {\n"); sb.Append(" _Client: ").Append(_Client).Append("\n"); sb.Append("}\n"); @@ -99,7 +99,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this._Client != null) - hashCode = hashCode * 59 + this._Client.GetHashCode(); + { + hashCode = (hashCode * 59) + this._Client.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs index 5432980b6bd..560d91db234 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Name.cs @@ -94,7 +94,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Name {\n"); sb.Append(" _Name: ").Append(_Name).Append("\n"); sb.Append(" SnakeCase: ").Append(SnakeCase).Append("\n"); @@ -142,11 +142,13 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Name.GetHashCode(); - hashCode = hashCode * 59 + this.SnakeCase.GetHashCode(); + hashCode = (hashCode * 59) + this._Name.GetHashCode(); + hashCode = (hashCode * 59) + this.SnakeCase.GetHashCode(); if (this.Property != null) - hashCode = hashCode * 59 + this.Property.GetHashCode(); - hashCode = hashCode * 59 + this._123Number.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Property.GetHashCode(); + } + hashCode = (hashCode * 59) + this._123Number.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs index 3a34e8cc128..57555c37678 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs @@ -142,7 +142,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); @@ -200,29 +200,53 @@ namespace Org.OpenAPITools.Model { int hashCode = base.GetHashCode(); if (this.IntegerProp != null) - hashCode = hashCode * 59 + this.IntegerProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); + } if (this.NumberProp != null) - hashCode = hashCode * 59 + this.NumberProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.NumberProp.GetHashCode(); + } if (this.BooleanProp != null) - hashCode = hashCode * 59 + this.BooleanProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.BooleanProp.GetHashCode(); + } if (this.StringProp != null) - hashCode = hashCode * 59 + this.StringProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.StringProp.GetHashCode(); + } if (this.DateProp != null) - hashCode = hashCode * 59 + this.DateProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DateProp.GetHashCode(); + } if (this.DatetimeProp != null) - hashCode = hashCode * 59 + this.DatetimeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DatetimeProp.GetHashCode(); + } if (this.ArrayNullableProp != null) - hashCode = hashCode * 59 + this.ArrayNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayNullableProp.GetHashCode(); + } if (this.ArrayAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ArrayAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayAndItemsNullableProp.GetHashCode(); + } if (this.ArrayItemsNullable != null) - hashCode = hashCode * 59 + this.ArrayItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ArrayItemsNullable.GetHashCode(); + } if (this.ObjectNullableProp != null) - hashCode = hashCode * 59 + this.ObjectNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectNullableProp.GetHashCode(); + } if (this.ObjectAndItemsNullableProp != null) - hashCode = hashCode * 59 + this.ObjectAndItemsNullableProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectAndItemsNullableProp.GetHashCode(); + } if (this.ObjectItemsNullable != null) - hashCode = hashCode * 59 + this.ObjectItemsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectItemsNullable.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NumberOnly.cs index 971605b38df..467579e6689 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class NumberOnly {\n"); sb.Append(" JustNumber: ").Append(JustNumber).Append("\n"); sb.Append("}\n"); @@ -98,7 +98,7 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.JustNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.JustNumber.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 893a33830b9..308018f5d23 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -80,7 +80,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ObjectWithDeprecatedFields {\n"); sb.Append(" Uuid: ").Append(Uuid).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); @@ -129,12 +129,18 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Uuid != null) - hashCode = hashCode * 59 + this.Uuid.GetHashCode(); - hashCode = hashCode * 59 + this.Id.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Uuid.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.DeprecatedRef != null) - hashCode = hashCode * 59 + this.DeprecatedRef.GetHashCode(); + { + hashCode = (hashCode * 59) + this.DeprecatedRef.GetHashCode(); + } if (this.Bars != null) - hashCode = hashCode * 59 + this.Bars.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bars.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Order.cs index b985923e023..306417b4a86 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Order.cs @@ -121,7 +121,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); @@ -171,13 +171,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); - hashCode = hashCode * 59 + this.PetId.GetHashCode(); - hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.PetId.GetHashCode(); + hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); if (this.ShipDate != null) - hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); - hashCode = hashCode * 59 + this.Complete.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + hashCode = (hashCode * 59) + this.Complete.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/OuterComposite.cs index a2f05013b0b..53d71534985 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class OuterComposite {\n"); sb.Append(" MyNumber: ").Append(MyNumber).Append("\n"); sb.Append(" MyString: ").Append(MyString).Append("\n"); @@ -116,10 +116,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.MyNumber.GetHashCode(); + hashCode = (hashCode * 59) + this.MyNumber.GetHashCode(); if (this.MyString != null) - hashCode = hashCode * 59 + this.MyString.GetHashCode(); - hashCode = hashCode * 59 + this.MyBoolean.GetHashCode(); + { + hashCode = (hashCode * 59) + this.MyString.GetHashCode(); + } + hashCode = (hashCode * 59) + this.MyBoolean.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ParentPet.cs index 7ddd99d4e0f..c9f4484a5a6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ParentPet.cs @@ -54,7 +54,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ParentPet {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append("}\n"); @@ -120,7 +120,10 @@ namespace Org.OpenAPITools.Model /// Validation Result protected IEnumerable BaseValidate(ValidationContext validationContext) { - foreach(var x in BaseValidate(validationContext)) yield return x; + foreach (var x in BaseValidate(validationContext)) + { + yield return x; + } yield break; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pet.cs index 1e864bcd01d..f540c101ec6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Pet.cs @@ -134,7 +134,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Category: ").Append(Category).Append("\n"); @@ -184,16 +184,24 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Category != null) - hashCode = hashCode * 59 + this.Category.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Category.GetHashCode(); + } if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.PhotoUrls != null) - hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); + } if (this.Tags != null) - hashCode = hashCode * 59 + this.Tags.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Tags.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index c55a39f75d2..09312553eca 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class QuadrilateralInterface {\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); sb.Append("}\n"); @@ -108,7 +108,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 08a4bf03ab3..1bf6cf2fdf5 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -67,7 +67,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ReadOnlyFirst {\n"); sb.Append(" Bar: ").Append(Bar).Append("\n"); sb.Append(" Baz: ").Append(Baz).Append("\n"); @@ -114,9 +114,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.Bar != null) - hashCode = hashCode * 59 + this.Bar.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Bar.GetHashCode(); + } if (this.Baz != null) - hashCode = hashCode * 59 + this.Baz.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Baz.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Return.cs index 8250818df72..250852d067c 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Return.cs @@ -53,7 +53,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Return {\n"); sb.Append(" _Return: ").Append(_Return).Append("\n"); sb.Append("}\n"); @@ -98,7 +98,7 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this._Return.GetHashCode(); + hashCode = (hashCode * 59) + this._Return.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 80bd3d4a178..f9dd3abd817 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ScaleneTriangle {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeInterface.cs index f147ffe20c5..00642181a1f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ShapeInterface {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append("}\n"); @@ -108,7 +108,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 019b6fddad7..14fe11a6529 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -74,7 +74,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SimpleQuadrilateral {\n"); sb.Append(" ShapeType: ").Append(ShapeType).Append("\n"); sb.Append(" QuadrilateralType: ").Append(QuadrilateralType).Append("\n"); @@ -121,9 +121,13 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.ShapeType != null) - hashCode = hashCode * 59 + this.ShapeType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShapeType.GetHashCode(); + } if (this.QuadrilateralType != null) - hashCode = hashCode * 59 + this.QuadrilateralType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.QuadrilateralType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SpecialModelName.cs index 0323c228a6f..8c202780cc1 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class SpecialModelName {\n"); sb.Append(" SpecialPropertyName: ").Append(SpecialPropertyName).Append("\n"); sb.Append(" _SpecialModelName: ").Append(_SpecialModelName).Append("\n"); @@ -107,9 +107,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.SpecialPropertyName.GetHashCode(); + hashCode = (hashCode * 59) + this.SpecialPropertyName.GetHashCode(); if (this._SpecialModelName != null) - hashCode = hashCode * 59 + this._SpecialModelName.GetHashCode(); + { + hashCode = (hashCode * 59) + this._SpecialModelName.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Tag.cs index df2fdd19141..a40a78f7267 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Tag.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Tag {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -107,9 +107,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TriangleInterface.cs index f2a5d1cb779..6eec5e9b935 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -62,7 +62,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class TriangleInterface {\n"); sb.Append(" TriangleType: ").Append(TriangleType).Append("\n"); sb.Append("}\n"); @@ -108,7 +108,9 @@ namespace Org.OpenAPITools.Model { int hashCode = 41; if (this.TriangleType != null) - hashCode = hashCode * 59 + this.TriangleType.GetHashCode(); + { + hashCode = (hashCode * 59) + this.TriangleType.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/User.cs index 07a5171eb90..874421d4655 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/User.cs @@ -146,7 +146,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); @@ -202,28 +202,48 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Username != null) - hashCode = hashCode * 59 + this.Username.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Username.GetHashCode(); + } if (this.FirstName != null) - hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); + } if (this.LastName != null) - hashCode = hashCode * 59 + this.LastName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.LastName.GetHashCode(); + } if (this.Email != null) - hashCode = hashCode * 59 + this.Email.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Email.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.Phone != null) - hashCode = hashCode * 59 + this.Phone.GetHashCode(); - hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Phone.GetHashCode(); + } + hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); if (this.ObjectWithNoDeclaredProps != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredProps.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredProps.GetHashCode(); + } if (this.ObjectWithNoDeclaredPropsNullable != null) - hashCode = hashCode * 59 + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ObjectWithNoDeclaredPropsNullable.GetHashCode(); + } if (this.AnyTypeProp != null) - hashCode = hashCode * 59 + this.AnyTypeProp.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypeProp.GetHashCode(); + } if (this.AnyTypePropNullable != null) - hashCode = hashCode * 59 + this.AnyTypePropNullable.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AnyTypePropNullable.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Whale.cs index 2795e2fe59f..74df24d5a8f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Whale.cs @@ -78,7 +78,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Whale {\n"); sb.Append(" HasBaleen: ").Append(HasBaleen).Append("\n"); sb.Append(" HasTeeth: ").Append(HasTeeth).Append("\n"); @@ -125,10 +125,12 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.HasBaleen.GetHashCode(); - hashCode = hashCode * 59 + this.HasTeeth.GetHashCode(); + hashCode = (hashCode * 59) + this.HasBaleen.GetHashCode(); + hashCode = (hashCode * 59) + this.HasTeeth.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs index bf9735fb37e..4fb60ed8ddf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs @@ -106,7 +106,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -154,11 +154,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = base.GetHashCode(); - hashCode = hashCode * 59 + this.Type.GetHashCode(); + hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) - hashCode = hashCode * 59 + this.ClassName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ClassName.GetHashCode(); + } if (this.AdditionalProperties != null) - hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs index 6f8809911e9..08b2900cec6 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/PetApi.cs @@ -538,7 +538,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -554,10 +556,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -570,11 +578,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -604,7 +614,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->AddPet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -620,12 +632,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -637,13 +654,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("AddPet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -680,10 +699,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -700,11 +725,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -743,12 +770,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (apiKey != null) @@ -764,13 +796,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeletePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -798,7 +832,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -812,10 +848,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -828,11 +870,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByStatus", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -862,7 +906,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'status' is set if (status == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'status' when calling PetApi->FindPetsByStatus"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -876,12 +922,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "status", status)); @@ -893,13 +944,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByStatus", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByStatus", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -929,7 +982,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -943,10 +998,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -959,11 +1020,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/pet/findByTags", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -995,7 +1058,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'tags' is set if (tags == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'tags' when calling PetApi->FindPetsByTags"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1009,12 +1074,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("csv", "tags", tags)); @@ -1026,13 +1096,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/pet/findByTags", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("FindPetsByTags", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1070,10 +1142,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1085,11 +1163,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1129,12 +1209,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter @@ -1145,13 +1230,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetPetById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1179,7 +1266,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1195,10 +1284,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1211,11 +1306,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/pet", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1245,7 +1342,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'pet' is set if (pet == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'pet' when calling PetApi->UpdatePet"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1261,12 +1360,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = pet; @@ -1278,13 +1382,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePet", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1324,10 +1430,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1348,11 +1460,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1394,12 +1508,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (name != null) @@ -1419,13 +1538,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdatePetWithForm", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1467,10 +1588,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1491,11 +1618,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1539,12 +1668,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("petId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(petId)); // path parameter if (additionalMetadata != null) @@ -1564,13 +1698,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/pet/{petId}/uploadImage", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UploadFile", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs index 67f8c23d6ca..81a9795bedf 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/StoreApi.cs @@ -345,7 +345,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -357,21 +359,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("orderId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Delete("/store/order/{orderId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -400,7 +410,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'orderId' is set if (orderId == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'orderId' when calling StoreApi->DeleteOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -412,24 +424,31 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("orderId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/store/order/{orderId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -464,10 +483,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -478,11 +503,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get>("/store/inventory", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -519,12 +546,17 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -534,13 +566,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync>("/store/inventory", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetInventory", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -578,21 +612,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("orderId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/store/order/{orderId}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -632,24 +674,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("orderId", Org.OpenAPITools.Client.ClientUtils.ParameterToString(orderId)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/store/order/{orderId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetOrderById", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -677,7 +726,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -692,21 +743,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request var localVarResponse = this.Client.Post("/store/order", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -736,7 +795,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'order' is set if (order == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'order' when calling StoreApi->PlaceOrder"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -751,24 +812,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = order; // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/store/order", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("PlaceOrder", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs index ac62b62f067..907a252179d 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Api/UserApi.cs @@ -517,7 +517,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -530,10 +532,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; @@ -545,11 +553,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/user", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -578,7 +588,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -591,12 +603,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; @@ -607,13 +624,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -640,7 +659,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -653,10 +674,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; @@ -668,11 +695,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithArray", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -701,7 +730,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithArrayInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -714,12 +745,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; @@ -730,13 +766,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithArray", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithArrayInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -763,7 +801,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -776,10 +816,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; @@ -791,11 +837,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Post("/user/createWithList", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -824,7 +872,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->CreateUsersWithListInput"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -837,12 +887,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.Data = user; @@ -853,13 +908,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PostAsync("/user/createWithList", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("CreateUsersWithListInput", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -886,7 +943,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -898,10 +957,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter @@ -913,11 +978,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Delete("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -946,7 +1013,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->DeleteUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -958,12 +1027,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter @@ -974,13 +1048,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.DeleteAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("DeleteUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1008,7 +1084,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1022,21 +1100,29 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request var localVarResponse = this.Client.Get("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1066,7 +1152,9 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->GetUserByName"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1080,24 +1168,31 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("GetUserByName", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1127,11 +1222,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1145,10 +1244,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); @@ -1156,11 +1261,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/user/login", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1192,11 +1299,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->LoginUser"); + } // verify the required parameter 'password' is set if (password == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'password' when calling UserApi->LoginUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1210,25 +1321,32 @@ namespace Org.OpenAPITools.Api "application/json" }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "username", username)); localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "password", password)); // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/login", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LoginUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1261,10 +1379,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -1275,11 +1399,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Get("/user/logout", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1314,12 +1440,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } // authentication (api_key) required @@ -1329,13 +1460,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.GetAsync("/user/logout", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("LogoutUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1364,11 +1497,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1381,10 +1518,16 @@ namespace Org.OpenAPITools.Api }; var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; @@ -1397,11 +1540,13 @@ namespace Org.OpenAPITools.Api // make the HTTP request var localVarResponse = this.Client.Put("/user/{username}", localVarRequestOptions, this.Configuration); - if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; @@ -1432,11 +1577,15 @@ namespace Org.OpenAPITools.Api { // verify the required parameter 'username' is set if (username == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'username' when calling UserApi->UpdateUser"); + } // verify the required parameter 'user' is set if (user == null) + { throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'user' when calling UserApi->UpdateUser"); + } Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -1449,12 +1598,17 @@ namespace Org.OpenAPITools.Api string[] _accepts = new string[] { }; - var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); - if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); - if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } localVarRequestOptions.PathParameters.Add("username", Org.OpenAPITools.Client.ClientUtils.ParameterToString(username)); // path parameter localVarRequestOptions.Data = user; @@ -1466,13 +1620,15 @@ namespace Org.OpenAPITools.Api } // make the HTTP request - var localVarResponse = await this.AsynchronousClient.PutAsync("/user/{username}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); if (this.ExceptionFactory != null) { Exception _exception = this.ExceptionFactory("UpdateUser", localVarResponse); - if (_exception != null) throw _exception; + if (_exception != null) + { + throw _exception; + } } return localVarResponse; diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/ApiResponse.cs index ab1912d31c8..cc3ceb025cb 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -69,7 +69,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class ApiResponse {\n"); sb.Append(" Code: ").Append(Code).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); @@ -116,11 +116,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Code.GetHashCode(); + hashCode = (hashCode * 59) + this.Code.GetHashCode(); if (this.Type != null) - hashCode = hashCode * 59 + this.Type.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Type.GetHashCode(); + } if (this.Message != null) - hashCode = hashCode * 59 + this.Message.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Message.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Category.cs index d6e998cd008..e1cd62ca772 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Category.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Category {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -107,9 +107,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Order.cs index 5abdf28d6a7..df6c3d1d138 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Order.cs @@ -121,7 +121,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); @@ -171,13 +171,15 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); - hashCode = hashCode * 59 + this.PetId.GetHashCode(); - hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.PetId.GetHashCode(); + hashCode = (hashCode * 59) + this.Quantity.GetHashCode(); if (this.ShipDate != null) - hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); - hashCode = hashCode * 59 + this.Complete.GetHashCode(); + { + hashCode = (hashCode * 59) + this.ShipDate.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); + hashCode = (hashCode * 59) + this.Complete.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Pet.cs index 7f9ca265490..0416d758d6f 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Pet.cs @@ -135,7 +135,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Category: ").Append(Category).Append("\n"); @@ -185,16 +185,24 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Category != null) - hashCode = hashCode * 59 + this.Category.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Category.GetHashCode(); + } if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } if (this.PhotoUrls != null) - hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + { + hashCode = (hashCode * 59) + this.PhotoUrls.GetHashCode(); + } if (this.Tags != null) - hashCode = hashCode * 59 + this.Tags.GetHashCode(); - hashCode = hashCode * 59 + this.Status.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Tags.GetHashCode(); + } + hashCode = (hashCode * 59) + this.Status.GetHashCode(); return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Tag.cs index caf1c640c2e..d0042987aae 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/Tag.cs @@ -61,7 +61,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class Tag {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); @@ -107,9 +107,11 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Name != null) - hashCode = hashCode * 59 + this.Name.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Name.GetHashCode(); + } return hashCode; } } diff --git a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/User.cs index aa0d4a26a81..8b03a001b07 100644 --- a/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp-netcore/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Model/User.cs @@ -110,7 +110,7 @@ namespace Org.OpenAPITools.Model /// String presentation of the object public override string ToString() { - var sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); @@ -162,20 +162,32 @@ namespace Org.OpenAPITools.Model unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = (hashCode * 59) + this.Id.GetHashCode(); if (this.Username != null) - hashCode = hashCode * 59 + this.Username.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Username.GetHashCode(); + } if (this.FirstName != null) - hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.FirstName.GetHashCode(); + } if (this.LastName != null) - hashCode = hashCode * 59 + this.LastName.GetHashCode(); + { + hashCode = (hashCode * 59) + this.LastName.GetHashCode(); + } if (this.Email != null) - hashCode = hashCode * 59 + this.Email.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Email.GetHashCode(); + } if (this.Password != null) - hashCode = hashCode * 59 + this.Password.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Password.GetHashCode(); + } if (this.Phone != null) - hashCode = hashCode * 59 + this.Phone.GetHashCode(); - hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + { + hashCode = (hashCode * 59) + this.Phone.GetHashCode(); + } + hashCode = (hashCode * 59) + this.UserStatus.GetHashCode(); return hashCode; } } From 08eaafa871b536e2f357fd282483f4bc797292c2 Mon Sep 17 00:00:00 2001 From: AJ Rice <53190766+ajrice6713@users.noreply.github.com> Date: Thu, 25 Nov 2021 01:17:50 -0500 Subject: [PATCH 25/61] Add operation level servers support for java okhttp-gson client (#10925) * Add Operation Servers to {operation}Call method * add getter/setter methods Add methods for hostIndex and customBaseUrl * Fix return types for getters * Add custom baseUrl logic if you dont specifically declare a custom base url using the set method then it uses the 1st server in the operation host index array if no custom url is set and the operation base path array is empty however, the call throws an exception * Update server selection logic First checks to see if a custom url is provided If not, checks to see if operation level server is defined and uses the supplied host index (default 0) If neither is supplied, uses the ApiClient default base path * Update samples and docs --- .../libraries/okhttp-gson/ApiClient.mustache | 16 +- .../Java/libraries/okhttp-gson/api.mustache | 34 ++- .../org/openapitools/client/ApiClient.java | 16 +- .../org/openapitools/client/api/PingApi.java | 34 ++- .../org/openapitools/client/ApiClient.java | 16 +- .../client/api/AnotherFakeApi.java | 34 ++- .../org/openapitools/client/api/FakeApi.java | 242 +++++++++++++++++- .../client/api/FakeClassnameTags123Api.java | 34 ++- .../org/openapitools/client/api/PetApi.java | 162 +++++++++++- .../org/openapitools/client/api/StoreApi.java | 82 +++++- .../org/openapitools/client/api/UserApi.java | 146 ++++++++++- .../org/openapitools/client/ApiClient.java | 16 +- .../client/api/AnotherFakeApi.java | 34 ++- .../org/openapitools/client/api/FakeApi.java | 242 +++++++++++++++++- .../client/api/FakeClassnameTags123Api.java | 34 ++- .../org/openapitools/client/api/PetApi.java | 162 +++++++++++- .../org/openapitools/client/api/StoreApi.java | 82 +++++- .../org/openapitools/client/api/UserApi.java | 146 ++++++++++- .../org/openapitools/client/ApiClient.java | 16 +- .../client/api/AnotherFakeApi.java | 34 ++- .../org/openapitools/client/api/FakeApi.java | 242 +++++++++++++++++- .../client/api/FakeClassnameTags123Api.java | 34 ++- .../org/openapitools/client/api/PetApi.java | 162 +++++++++++- .../org/openapitools/client/api/StoreApi.java | 82 +++++- .../org/openapitools/client/api/UserApi.java | 146 ++++++++++- 25 files changed, 2105 insertions(+), 143 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index 732551cec58..a0c3c4e5b7c 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -1314,8 +1314,8 @@ public class ApiClient { * @return The HTTP call * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Call buildCall(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); return httpClient.newCall(request); } @@ -1336,12 +1336,12 @@ public class ApiClient { * @return The HTTP request * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Request buildRequest(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams List allQueryParams = new ArrayList(queryParams); allQueryParams.addAll(collectionQueryParams); - final String url = buildUrl(path, queryParams, collectionQueryParams); + final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); // prepare HTTP request body RequestBody reqBody; @@ -1396,9 +1396,13 @@ public class ApiClient { * @param collectionQueryParams The collection query parameters * @return The full URL */ - public String buildUrl(String path, List queryParams, List collectionQueryParams) { + public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); + if (baseUrl != null) { + url.append(baseUrl).append(path); + } else { + url.append(basePath).append(path); + } if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache index 525d56fa5d5..50b7cfc5ed5 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -55,6 +55,8 @@ import java.io.InputStream; {{#operations}} public class {{classname}} { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public {{classname}}() { this(Configuration.getDefaultApiClient()); @@ -72,6 +74,22 @@ public class {{classname}} { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + {{#operation}} {{^vendorExtensions.x-group-parameters}}/** * Build call for {{operationId}}{{#allParams}} @@ -100,6 +118,20 @@ public class {{classname}} { @Deprecated {{/isDeprecated}} public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { {{#servers}}"{{{url}}}"{{^-last}}, {{/-last}}{{/servers}} }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; // create path and map variables @@ -177,7 +209,7 @@ public class {{classname}} { } String[] localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}} }; - return localVarApiClient.buildCall(localVarPath, {{^dynamicOperations}}"{{httpMethod}}"{{/dynamicOperations}}{{#dynamicOperations}}apiOperation.getMethod(){{/dynamicOperations}}, localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, {{^dynamicOperations}}"{{httpMethod}}"{{/dynamicOperations}}{{#dynamicOperations}}apiOperation.getMethod(){{/dynamicOperations}}, localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } {{#isDeprecated}} diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java index 443b6003638..843d13b69a1 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java @@ -1102,8 +1102,8 @@ public class ApiClient { * @return The HTTP call * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Call buildCall(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); return httpClient.newCall(request); } @@ -1124,12 +1124,12 @@ public class ApiClient { * @return The HTTP request * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Request buildRequest(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams List allQueryParams = new ArrayList(queryParams); allQueryParams.addAll(collectionQueryParams); - final String url = buildUrl(path, queryParams, collectionQueryParams); + final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); // prepare HTTP request body RequestBody reqBody; @@ -1184,9 +1184,13 @@ public class ApiClient { * @param collectionQueryParams The collection query parameters * @return The full URL */ - public String buildUrl(String path, List queryParams, List collectionQueryParams) { + public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); + if (baseUrl != null) { + url.append(baseUrl).append(path); + } else { + url.append(basePath).append(path); + } if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/api/PingApi.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/api/PingApi.java index c29f49e68a3..2f60324f376 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/api/PingApi.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/api/PingApi.java @@ -38,6 +38,8 @@ import java.io.InputStream; public class PingApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public PingApi() { this(Configuration.getDefaultApiClient()); @@ -55,6 +57,22 @@ public class PingApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for postPing * @param someObj (optional) @@ -68,6 +86,20 @@ public class PingApi { */ public okhttp3.Call postPingCall(SomeObj someObj, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = someObj; // create path and map variables @@ -96,7 +128,7 @@ public class PingApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java index 32fb9f79f0f..69d6469c85a 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java @@ -1180,8 +1180,8 @@ public class ApiClient { * @return The HTTP call * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Call buildCall(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); return httpClient.newCall(request); } @@ -1202,12 +1202,12 @@ public class ApiClient { * @return The HTTP request * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Request buildRequest(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams List allQueryParams = new ArrayList(queryParams); allQueryParams.addAll(collectionQueryParams); - final String url = buildUrl(path, queryParams, collectionQueryParams); + final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); // prepare HTTP request body RequestBody reqBody; @@ -1262,9 +1262,13 @@ public class ApiClient { * @param collectionQueryParams The collection query parameters * @return The full URL */ - public String buildUrl(String path, List queryParams, List collectionQueryParams) { + public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); + if (baseUrl != null) { + url.append(baseUrl).append(path); + } else { + url.append(basePath).append(path); + } if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index c93b4ce865a..f85c9c873bf 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -40,6 +40,8 @@ import java.util.Map; public class AnotherFakeApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public AnotherFakeApi() { this(Configuration.getDefaultApiClient()); @@ -57,6 +59,22 @@ public class AnotherFakeApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for call123testSpecialTags * @param body client model (required) @@ -70,6 +88,20 @@ public class AnotherFakeApi { */ public okhttp3.Call call123testSpecialTagsCall(Client body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -106,7 +138,7 @@ public class AnotherFakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/FakeApi.java index 06844d6e641..5052c1b986c 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/FakeApi.java @@ -48,6 +48,8 @@ import java.util.Map; public class FakeApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public FakeApi() { this(Configuration.getDefaultApiClient()); @@ -65,6 +67,22 @@ public class FakeApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for createXmlItem * @param xmlItem XmlItem Body (required) @@ -78,6 +96,20 @@ public class FakeApi { */ public okhttp3.Call createXmlItemCall(XmlItem xmlItem, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = xmlItem; // create path and map variables @@ -114,7 +146,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -195,6 +227,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterBooleanSerializeCall(Boolean body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -231,7 +277,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -311,6 +357,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterCompositeSerializeCall(OuterComposite body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -347,7 +407,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -427,6 +487,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterNumberSerializeCall(BigDecimal body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -463,7 +537,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -543,6 +617,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterStringSerializeCall(String body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -579,7 +667,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -659,6 +747,20 @@ public class FakeApi { */ public okhttp3.Call testBodyWithFileSchemaCall(FileSchemaTestClass body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -695,7 +797,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -777,6 +879,20 @@ public class FakeApi { */ public okhttp3.Call testBodyWithQueryParamsCall(String query, User body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -814,7 +930,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -903,6 +1019,20 @@ public class FakeApi { */ public okhttp3.Call testClientModelCall(Client body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -939,7 +1069,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1038,6 +1168,20 @@ public class FakeApi { */ public okhttp3.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1130,7 +1274,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { "http_basic_test" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1276,6 +1420,20 @@ public class FakeApi { */ public okhttp3.Call testEnumParametersCall(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1326,7 +1484,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1414,6 +1572,20 @@ public class FakeApi { return localVarCall; } private okhttp3.Call testGroupParametersCall(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1456,7 +1628,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1627,6 +1799,20 @@ public class FakeApi { */ public okhttp3.Call testInlineAdditionalPropertiesCall(Map param, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = param; // create path and map variables @@ -1663,7 +1849,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1745,6 +1931,20 @@ public class FakeApi { */ public okhttp3.Call testJsonFormDataCall(String param, String param2, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1789,7 +1989,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1882,6 +2082,20 @@ public class FakeApi { */ public okhttp3.Call testQueryParameterCollectionFormatCall(List pipe, List ioutil, List http, List url, List context, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1923,7 +2137,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index ab4032b3ba4..fcef8d5e735 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -40,6 +40,8 @@ import java.util.Map; public class FakeClassnameTags123Api { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public FakeClassnameTags123Api() { this(Configuration.getDefaultApiClient()); @@ -57,6 +59,22 @@ public class FakeClassnameTags123Api { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for testClassname * @param body client model (required) @@ -70,6 +88,20 @@ public class FakeClassnameTags123Api { */ public okhttp3.Call testClassnameCall(Client body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -106,7 +138,7 @@ public class FakeClassnameTags123Api { } String[] localVarAuthNames = new String[] { "api_key_query" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/PetApi.java index 164b243db0a..2171c8f1a0d 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/PetApi.java @@ -43,6 +43,8 @@ import java.util.Map; public class PetApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public PetApi() { this(Configuration.getDefaultApiClient()); @@ -60,6 +62,22 @@ public class PetApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for addPet * @param body Pet object that needs to be added to the store (required) @@ -74,6 +92,20 @@ public class PetApi { */ public okhttp3.Call addPetCall(Pet body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -110,7 +142,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -196,6 +228,20 @@ public class PetApi { */ public okhttp3.Call deletePetCall(Long petId, String apiKey, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -234,7 +280,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -322,6 +368,20 @@ public class PetApi { */ public okhttp3.Call findPetsByStatusCall(List status, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -359,7 +419,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -450,6 +510,20 @@ public class PetApi { */ @Deprecated public okhttp3.Call findPetsByTagsCall(Set tags, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -487,7 +561,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @Deprecated @@ -584,6 +658,20 @@ public class PetApi { */ public okhttp3.Call getPetByIdCall(Long petId, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -621,7 +709,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "api_key" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -715,6 +803,20 @@ public class PetApi { */ public okhttp3.Call updatePetCall(Pet body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -751,7 +853,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -843,6 +945,20 @@ public class PetApi { */ public okhttp3.Call updatePetWithFormCall(Long petId, String name, String status, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -888,7 +1004,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -977,6 +1093,20 @@ public class PetApi { */ public okhttp3.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1022,7 +1152,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1115,6 +1245,20 @@ public class PetApi { */ public okhttp3.Call uploadFileWithRequiredFileCall(Long petId, File requiredFile, String additionalMetadata, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1160,7 +1304,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/StoreApi.java index 795c365962f..a2d86c9f541 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/StoreApi.java @@ -40,6 +40,8 @@ import java.util.Map; public class StoreApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public StoreApi() { this(Configuration.getDefaultApiClient()); @@ -57,6 +59,22 @@ public class StoreApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for deleteOrder * @param orderId ID of the order that needs to be deleted (required) @@ -71,6 +89,20 @@ public class StoreApi { */ public okhttp3.Call deleteOrderCall(String orderId, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -108,7 +140,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -191,6 +223,20 @@ public class StoreApi { */ public okhttp3.Call getInventoryCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -227,7 +273,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { "api_key" }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -306,6 +352,20 @@ public class StoreApi { */ public okhttp3.Call getOrderByIdCall(Long orderId, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -343,7 +403,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -435,6 +495,20 @@ public class StoreApi { */ public okhttp3.Call placeOrderCall(Order body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -471,7 +545,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/UserApi.java index 63385ff3554..b6ab5b1bd53 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/api/UserApi.java @@ -40,6 +40,8 @@ import java.util.Map; public class UserApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public UserApi() { this(Configuration.getDefaultApiClient()); @@ -57,6 +59,22 @@ public class UserApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for createUser * @param body Created user object (required) @@ -70,6 +88,20 @@ public class UserApi { */ public okhttp3.Call createUserCall(User body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -106,7 +138,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -187,6 +219,20 @@ public class UserApi { */ public okhttp3.Call createUsersWithArrayInputCall(List body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -223,7 +269,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -304,6 +350,20 @@ public class UserApi { */ public okhttp3.Call createUsersWithListInputCall(List body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -340,7 +400,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -422,6 +482,20 @@ public class UserApi { */ public okhttp3.Call deleteUserCall(String username, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -459,7 +533,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -545,6 +619,20 @@ public class UserApi { */ public okhttp3.Call getUserByNameCall(String username, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -582,7 +670,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -675,6 +763,20 @@ public class UserApi { */ public okhttp3.Call loginUserCall(String username, String password, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -713,7 +815,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -808,6 +910,20 @@ public class UserApi { */ public okhttp3.Call logoutUserCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -844,7 +960,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -919,6 +1035,20 @@ public class UserApi { */ public okhttp3.Call updateUserCall(String username, User body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -956,7 +1086,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, apiOperation.getMethod(), localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java index 67508f676bf..7ef420e3c7c 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java @@ -1181,8 +1181,8 @@ public class ApiClient { * @return The HTTP call * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Call buildCall(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); return httpClient.newCall(request); } @@ -1203,12 +1203,12 @@ public class ApiClient { * @return The HTTP request * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Request buildRequest(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams List allQueryParams = new ArrayList(queryParams); allQueryParams.addAll(collectionQueryParams); - final String url = buildUrl(path, queryParams, collectionQueryParams); + final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); // prepare HTTP request body RequestBody reqBody; @@ -1263,9 +1263,13 @@ public class ApiClient { * @param collectionQueryParams The collection query parameters * @return The full URL */ - public String buildUrl(String path, List queryParams, List collectionQueryParams) { + public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); + if (baseUrl != null) { + url.append(baseUrl).append(path); + } else { + url.append(basePath).append(path); + } if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 7bfa5d1220e..07dd5b37fb2 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -37,6 +37,8 @@ import java.util.Map; public class AnotherFakeApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public AnotherFakeApi() { this(Configuration.getDefaultApiClient()); @@ -54,6 +56,22 @@ public class AnotherFakeApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for call123testSpecialTags * @param body client model (required) @@ -67,6 +85,20 @@ public class AnotherFakeApi { */ public okhttp3.Call call123testSpecialTagsCall(Client body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -95,7 +127,7 @@ public class AnotherFakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeApi.java index 28d018f4bc4..7c1a5959f08 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeApi.java @@ -45,6 +45,8 @@ import java.util.Map; public class FakeApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public FakeApi() { this(Configuration.getDefaultApiClient()); @@ -62,6 +64,22 @@ public class FakeApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for createXmlItem * @param xmlItem XmlItem Body (required) @@ -75,6 +93,20 @@ public class FakeApi { */ public okhttp3.Call createXmlItemCall(XmlItem xmlItem, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = xmlItem; // create path and map variables @@ -103,7 +135,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -184,6 +216,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterBooleanSerializeCall(Boolean body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -212,7 +258,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -292,6 +338,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterCompositeSerializeCall(OuterComposite body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -320,7 +380,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -400,6 +460,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterNumberSerializeCall(BigDecimal body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -428,7 +502,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -508,6 +582,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterStringSerializeCall(String body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -536,7 +624,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -616,6 +704,20 @@ public class FakeApi { */ public okhttp3.Call testBodyWithFileSchemaCall(FileSchemaTestClass body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -644,7 +746,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -726,6 +828,20 @@ public class FakeApi { */ public okhttp3.Call testBodyWithQueryParamsCall(String query, User body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -758,7 +874,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -847,6 +963,20 @@ public class FakeApi { */ public okhttp3.Call testClientModelCall(Client body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -875,7 +1005,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -974,6 +1104,20 @@ public class FakeApi { */ public okhttp3.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1058,7 +1202,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { "http_basic_test" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1204,6 +1348,20 @@ public class FakeApi { */ public okhttp3.Call testEnumParametersCall(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1264,7 +1422,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1352,6 +1510,20 @@ public class FakeApi { return localVarCall; } private okhttp3.Call testGroupParametersCall(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1404,7 +1576,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1575,6 +1747,20 @@ public class FakeApi { */ public okhttp3.Call testInlineAdditionalPropertiesCall(Map param, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = param; // create path and map variables @@ -1603,7 +1789,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1685,6 +1871,20 @@ public class FakeApi { */ public okhttp3.Call testJsonFormDataCall(String param, String param2, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1721,7 +1921,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1814,6 +2014,20 @@ public class FakeApi { */ public okhttp3.Call testQueryParameterCollectionFormatCall(List pipe, List ioutil, List http, List url, List context, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1862,7 +2076,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 54cef2eb37b..6073bb91da6 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -37,6 +37,8 @@ import java.util.Map; public class FakeClassnameTags123Api { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public FakeClassnameTags123Api() { this(Configuration.getDefaultApiClient()); @@ -54,6 +56,22 @@ public class FakeClassnameTags123Api { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for testClassname * @param body client model (required) @@ -67,6 +85,20 @@ public class FakeClassnameTags123Api { */ public okhttp3.Call testClassnameCall(Client body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -95,7 +127,7 @@ public class FakeClassnameTags123Api { } String[] localVarAuthNames = new String[] { "api_key_query" }; - return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/PetApi.java index 71a69f58786..6f6083f2d2c 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/PetApi.java @@ -40,6 +40,8 @@ import java.util.Map; public class PetApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public PetApi() { this(Configuration.getDefaultApiClient()); @@ -57,6 +59,22 @@ public class PetApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for addPet * @param body Pet object that needs to be added to the store (required) @@ -71,6 +89,20 @@ public class PetApi { */ public okhttp3.Call addPetCall(Pet body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -99,7 +131,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -185,6 +217,20 @@ public class PetApi { */ public okhttp3.Call deletePetCall(Long petId, String apiKey, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -218,7 +264,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -306,6 +352,20 @@ public class PetApi { */ public okhttp3.Call findPetsByStatusCall(List status, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -338,7 +398,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -429,6 +489,20 @@ public class PetApi { */ @Deprecated public okhttp3.Call findPetsByTagsCall(Set tags, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -461,7 +535,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @Deprecated @@ -558,6 +632,20 @@ public class PetApi { */ public okhttp3.Call getPetByIdCall(Long petId, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -587,7 +675,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "api_key" }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -681,6 +769,20 @@ public class PetApi { */ public okhttp3.Call updatePetCall(Pet body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -709,7 +811,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -801,6 +903,20 @@ public class PetApi { */ public okhttp3.Call updatePetWithFormCall(Long petId, String name, String status, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -838,7 +954,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -927,6 +1043,20 @@ public class PetApi { */ public okhttp3.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -964,7 +1094,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1057,6 +1187,20 @@ public class PetApi { */ public okhttp3.Call uploadFileWithRequiredFileCall(Long petId, File requiredFile, String additionalMetadata, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1094,7 +1238,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/StoreApi.java index 13b63b31ec1..21960166fd9 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/StoreApi.java @@ -37,6 +37,8 @@ import java.util.Map; public class StoreApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public StoreApi() { this(Configuration.getDefaultApiClient()); @@ -54,6 +56,22 @@ public class StoreApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for deleteOrder * @param orderId ID of the order that needs to be deleted (required) @@ -68,6 +86,20 @@ public class StoreApi { */ public okhttp3.Call deleteOrderCall(String orderId, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -97,7 +129,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -180,6 +212,20 @@ public class StoreApi { */ public okhttp3.Call getInventoryCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -208,7 +254,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { "api_key" }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -287,6 +333,20 @@ public class StoreApi { */ public okhttp3.Call getOrderByIdCall(Long orderId, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -316,7 +376,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -408,6 +468,20 @@ public class StoreApi { */ public okhttp3.Call placeOrderCall(Order body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -436,7 +510,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/UserApi.java index af4538427c1..7e6577a7b11 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/api/UserApi.java @@ -37,6 +37,8 @@ import java.util.Map; public class UserApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public UserApi() { this(Configuration.getDefaultApiClient()); @@ -54,6 +56,22 @@ public class UserApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for createUser * @param body Created user object (required) @@ -67,6 +85,20 @@ public class UserApi { */ public okhttp3.Call createUserCall(User body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -95,7 +127,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -176,6 +208,20 @@ public class UserApi { */ public okhttp3.Call createUsersWithArrayInputCall(List body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -204,7 +250,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -285,6 +331,20 @@ public class UserApi { */ public okhttp3.Call createUsersWithListInputCall(List body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -313,7 +373,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -395,6 +455,20 @@ public class UserApi { */ public okhttp3.Call deleteUserCall(String username, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -424,7 +498,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -510,6 +584,20 @@ public class UserApi { */ public okhttp3.Call getUserByNameCall(String username, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -539,7 +627,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -632,6 +720,20 @@ public class UserApi { */ public okhttp3.Call loginUserCall(String username, String password, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -668,7 +770,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -763,6 +865,20 @@ public class UserApi { */ public okhttp3.Call logoutUserCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -791,7 +907,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -866,6 +982,20 @@ public class UserApi { */ public okhttp3.Call updateUserCall(String username, User body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -895,7 +1025,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java index 67508f676bf..7ef420e3c7c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java @@ -1181,8 +1181,8 @@ public class ApiClient { * @return The HTTP call * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Call buildCall(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { - Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); return httpClient.newCall(request); } @@ -1203,12 +1203,12 @@ public class ApiClient { * @return The HTTP request * @throws org.openapitools.client.ApiException If fail to serialize the request body object */ - public Request buildRequest(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams List allQueryParams = new ArrayList(queryParams); allQueryParams.addAll(collectionQueryParams); - final String url = buildUrl(path, queryParams, collectionQueryParams); + final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); // prepare HTTP request body RequestBody reqBody; @@ -1263,9 +1263,13 @@ public class ApiClient { * @param collectionQueryParams The collection query parameters * @return The full URL */ - public String buildUrl(String path, List queryParams, List collectionQueryParams) { + public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { final StringBuilder url = new StringBuilder(); - url.append(basePath).append(path); + if (baseUrl != null) { + url.append(baseUrl).append(path); + } else { + url.append(basePath).append(path); + } if (queryParams != null && !queryParams.isEmpty()) { // support (constant) query string in `path`, e.g. "/posts?draft=1" diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 7bfa5d1220e..07dd5b37fb2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -37,6 +37,8 @@ import java.util.Map; public class AnotherFakeApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public AnotherFakeApi() { this(Configuration.getDefaultApiClient()); @@ -54,6 +56,22 @@ public class AnotherFakeApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for call123testSpecialTags * @param body client model (required) @@ -67,6 +85,20 @@ public class AnotherFakeApi { */ public okhttp3.Call call123testSpecialTagsCall(Client body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -95,7 +127,7 @@ public class AnotherFakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java index 28d018f4bc4..7c1a5959f08 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java @@ -45,6 +45,8 @@ import java.util.Map; public class FakeApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public FakeApi() { this(Configuration.getDefaultApiClient()); @@ -62,6 +64,22 @@ public class FakeApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for createXmlItem * @param xmlItem XmlItem Body (required) @@ -75,6 +93,20 @@ public class FakeApi { */ public okhttp3.Call createXmlItemCall(XmlItem xmlItem, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = xmlItem; // create path and map variables @@ -103,7 +135,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -184,6 +216,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterBooleanSerializeCall(Boolean body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -212,7 +258,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -292,6 +338,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterCompositeSerializeCall(OuterComposite body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -320,7 +380,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -400,6 +460,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterNumberSerializeCall(BigDecimal body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -428,7 +502,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -508,6 +582,20 @@ public class FakeApi { */ public okhttp3.Call fakeOuterStringSerializeCall(String body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -536,7 +624,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -616,6 +704,20 @@ public class FakeApi { */ public okhttp3.Call testBodyWithFileSchemaCall(FileSchemaTestClass body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -644,7 +746,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -726,6 +828,20 @@ public class FakeApi { */ public okhttp3.Call testBodyWithQueryParamsCall(String query, User body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -758,7 +874,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -847,6 +963,20 @@ public class FakeApi { */ public okhttp3.Call testClientModelCall(Client body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -875,7 +1005,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -974,6 +1104,20 @@ public class FakeApi { */ public okhttp3.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1058,7 +1202,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { "http_basic_test" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1204,6 +1348,20 @@ public class FakeApi { */ public okhttp3.Call testEnumParametersCall(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1264,7 +1422,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1352,6 +1510,20 @@ public class FakeApi { return localVarCall; } private okhttp3.Call testGroupParametersCall(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1404,7 +1576,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1575,6 +1747,20 @@ public class FakeApi { */ public okhttp3.Call testInlineAdditionalPropertiesCall(Map param, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = param; // create path and map variables @@ -1603,7 +1789,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1685,6 +1871,20 @@ public class FakeApi { */ public okhttp3.Call testJsonFormDataCall(String param, String param2, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1721,7 +1921,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1814,6 +2014,20 @@ public class FakeApi { */ public okhttp3.Call testQueryParameterCollectionFormatCall(List pipe, List ioutil, List http, List url, List context, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1862,7 +2076,7 @@ public class FakeApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 54cef2eb37b..6073bb91da6 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -37,6 +37,8 @@ import java.util.Map; public class FakeClassnameTags123Api { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public FakeClassnameTags123Api() { this(Configuration.getDefaultApiClient()); @@ -54,6 +56,22 @@ public class FakeClassnameTags123Api { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for testClassname * @param body client model (required) @@ -67,6 +85,20 @@ public class FakeClassnameTags123Api { */ public okhttp3.Call testClassnameCall(Client body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -95,7 +127,7 @@ public class FakeClassnameTags123Api { } String[] localVarAuthNames = new String[] { "api_key_query" }; - return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/PetApi.java index 71a69f58786..6f6083f2d2c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/PetApi.java @@ -40,6 +40,8 @@ import java.util.Map; public class PetApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public PetApi() { this(Configuration.getDefaultApiClient()); @@ -57,6 +59,22 @@ public class PetApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for addPet * @param body Pet object that needs to be added to the store (required) @@ -71,6 +89,20 @@ public class PetApi { */ public okhttp3.Call addPetCall(Pet body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -99,7 +131,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -185,6 +217,20 @@ public class PetApi { */ public okhttp3.Call deletePetCall(Long petId, String apiKey, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -218,7 +264,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -306,6 +352,20 @@ public class PetApi { */ public okhttp3.Call findPetsByStatusCall(List status, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -338,7 +398,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -429,6 +489,20 @@ public class PetApi { */ @Deprecated public okhttp3.Call findPetsByTagsCall(Set tags, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -461,7 +535,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @Deprecated @@ -558,6 +632,20 @@ public class PetApi { */ public okhttp3.Call getPetByIdCall(Long petId, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -587,7 +675,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "api_key" }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -681,6 +769,20 @@ public class PetApi { */ public okhttp3.Call updatePetCall(Pet body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -709,7 +811,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -801,6 +903,20 @@ public class PetApi { */ public okhttp3.Call updatePetWithFormCall(Long petId, String name, String status, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -838,7 +954,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -927,6 +1043,20 @@ public class PetApi { */ public okhttp3.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -964,7 +1094,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -1057,6 +1187,20 @@ public class PetApi { */ public okhttp3.Call uploadFileWithRequiredFileCall(Long petId, File requiredFile, String additionalMetadata, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -1094,7 +1238,7 @@ public class PetApi { } String[] localVarAuthNames = new String[] { "petstore_auth" }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/StoreApi.java index 13b63b31ec1..21960166fd9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/StoreApi.java @@ -37,6 +37,8 @@ import java.util.Map; public class StoreApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public StoreApi() { this(Configuration.getDefaultApiClient()); @@ -54,6 +56,22 @@ public class StoreApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for deleteOrder * @param orderId ID of the order that needs to be deleted (required) @@ -68,6 +86,20 @@ public class StoreApi { */ public okhttp3.Call deleteOrderCall(String orderId, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -97,7 +129,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -180,6 +212,20 @@ public class StoreApi { */ public okhttp3.Call getInventoryCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -208,7 +254,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { "api_key" }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -287,6 +333,20 @@ public class StoreApi { */ public okhttp3.Call getOrderByIdCall(Long orderId, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -316,7 +376,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -408,6 +468,20 @@ public class StoreApi { */ public okhttp3.Call placeOrderCall(Order body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -436,7 +510,7 @@ public class StoreApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/UserApi.java index af4538427c1..7e6577a7b11 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/UserApi.java @@ -37,6 +37,8 @@ import java.util.Map; public class UserApi { private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; public UserApi() { this(Configuration.getDefaultApiClient()); @@ -54,6 +56,22 @@ public class UserApi { this.localVarApiClient = apiClient; } + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + /** * Build call for createUser * @param body Created user object (required) @@ -67,6 +85,20 @@ public class UserApi { */ public okhttp3.Call createUserCall(User body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -95,7 +127,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -176,6 +208,20 @@ public class UserApi { */ public okhttp3.Call createUsersWithArrayInputCall(List body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -204,7 +250,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -285,6 +331,20 @@ public class UserApi { */ public okhttp3.Call createUsersWithListInputCall(List body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -313,7 +373,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -395,6 +455,20 @@ public class UserApi { */ public okhttp3.Call deleteUserCall(String username, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -424,7 +498,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -510,6 +584,20 @@ public class UserApi { */ public okhttp3.Call getUserByNameCall(String username, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -539,7 +627,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -632,6 +720,20 @@ public class UserApi { */ public okhttp3.Call loginUserCall(String username, String password, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -668,7 +770,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -763,6 +865,20 @@ public class UserApi { */ public okhttp3.Call logoutUserCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = null; // create path and map variables @@ -791,7 +907,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") @@ -866,6 +982,20 @@ public class UserApi { */ public okhttp3.Call updateUserCall(String username, User body, final ApiCallback _callback) throws ApiException { + String basePath = null; + + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + Object localVarPostBody = body; // create path and map variables @@ -895,7 +1025,7 @@ public class UserApi { } String[] localVarAuthNames = new String[] { }; - return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + return localVarApiClient.buildCall(basePath, localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); } @SuppressWarnings("rawtypes") From 5bd045289397c41973a0254a79fa9703ced799cc Mon Sep 17 00:00:00 2001 From: Steve Mason Date: Thu, 25 Nov 2021 06:44:57 +0000 Subject: [PATCH 26/61] [Java][Native] Drain InputStream when no response is being read (#10956) The [docs for ofInputStream](https://docs.oracle.com/en/java/javase/11/docs/api/java.net.http/java/net/http/HttpResponse.BodySubscribers.html#ofInputStream()) say: > To ensure that all resources associated with the corresponding exchange are properly released the caller must ensure to either read all lines until the stream is exhausted, or call BaseStream.close() if it is unable or unwilling to do so. Calling close before exhausting the stream may cause the underlying HTTP connection to be closed and prevent it from being reused for subsequent operations. When ObjectMapper.readValue is called with an InputStream it implicitly closes it, but when the library is not expecting a return type it's not passing the InputStream to Jackson, so the stream needs to be manually drained and closed as per the docs Failure to do this leads to a leak of HttpClient socket handles, and ultimately the exception `java.net.BindException: Cannot assign requested address` when trying to make API calls --- .../Java/libraries/native/api.mustache | 21 +- .../client/api/AnotherFakeApi.java | 14 +- .../org/openapitools/client/api/FakeApi.java | 223 +++++++++++++----- .../client/api/FakeClassnameTags123Api.java | 14 +- .../org/openapitools/client/api/PetApi.java | 138 +++++++---- .../org/openapitools/client/api/StoreApi.java | 59 +++-- .../org/openapitools/client/api/UserApi.java | 130 +++++++--- 7 files changed, 429 insertions(+), 170 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache index 018f51b32ce..218a432d106 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/api.mustache @@ -222,14 +222,25 @@ public class {{classname}} { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("{{operationId}}", localVarResponse); - } - return new ApiResponse<{{{returnType}}}{{^returnType}}Void{{/returnType}}>( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("{{operationId}}", localVarResponse); + } + return new ApiResponse<{{{returnType}}}{{^returnType}}Void{{/returnType}}>( localVarResponse.statusCode(), localVarResponse.headers().map(), - {{#returnType}}memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference<{{{returnType}}}>() {}){{/returnType}}{{^returnType}}null{{/returnType}} + {{#returnType}}memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference<{{{returnType}}}>() {}) // closes the InputStream{{/returnType}} + {{^returnType}}null{{/returnType}} ); + } finally { + {{^returnType}} + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + {{/returnType}} + } } catch (IOException e) { throw new ApiException(e); } diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index e553b758ccf..cacc3ac7cf4 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -102,14 +102,18 @@ public class AnotherFakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("call123testSpecialTags", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("call123testSpecialTags", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java index 36f4539d7cc..6618620891c 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java @@ -108,14 +108,23 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("createXmlItem", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("createXmlItem", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -182,14 +191,18 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fakeOuterBooleanSerialize", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("fakeOuterBooleanSerialize", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -252,14 +265,18 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fakeOuterCompositeSerialize", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("fakeOuterCompositeSerialize", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -322,14 +339,18 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fakeOuterNumberSerialize", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("fakeOuterNumberSerialize", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -392,14 +413,18 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("fakeOuterStringSerialize", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("fakeOuterStringSerialize", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -460,14 +485,23 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testBodyWithFileSchema", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testBodyWithFileSchema", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -534,14 +568,23 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testBodyWithQueryParams", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testBodyWithQueryParams", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -621,14 +664,18 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testClientModel", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testClientModel", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -719,14 +766,23 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testEndpointParameters", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testEndpointParameters", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -811,14 +867,23 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testEnumParameters", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testEnumParameters", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -934,14 +999,23 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testGroupParameters", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testGroupParameters", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -1103,14 +1177,23 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testInlineAdditionalProperties", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testInlineAdditionalProperties", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -1177,14 +1260,23 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testJsonFormData", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testJsonFormData", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -1255,14 +1347,23 @@ public class FakeApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testQueryParameterCollectionFormat", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testQueryParameterCollectionFormat", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 565c5651c18..b85f5608319 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -102,14 +102,18 @@ public class FakeClassnameTags123Api { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("testClassname", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testClassname", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java index a754fb97777..758142dfa7b 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/PetApi.java @@ -103,14 +103,23 @@ public class PetApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("addPet", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("addPet", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -177,14 +186,23 @@ public class PetApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("deletePet", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("deletePet", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -249,14 +267,18 @@ public class PetApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("findPetsByStatus", localVarResponse); - } - return new ApiResponse>( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("findPetsByStatus", localVarResponse); + } + return new ApiResponse>( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -330,14 +352,18 @@ public class PetApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("findPetsByTags", localVarResponse); - } - return new ApiResponse>( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("findPetsByTags", localVarResponse); + } + return new ApiResponse>( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -407,14 +433,18 @@ public class PetApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("getPetById", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("getPetById", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -474,14 +504,23 @@ public class PetApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("updatePet", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("updatePet", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -550,14 +589,23 @@ public class PetApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("updatePetWithForm", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("updatePetWithForm", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -623,14 +671,18 @@ public class PetApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("uploadFile", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("uploadFile", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -696,14 +748,18 @@ public class PetApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("uploadFileWithRequiredFile", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("uploadFileWithRequiredFile", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java index 2d691aec852..bde07853f96 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/StoreApi.java @@ -100,14 +100,23 @@ public class StoreApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("deleteOrder", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("deleteOrder", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -167,14 +176,18 @@ public class StoreApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("getInventory", localVarResponse); - } - return new ApiResponse>( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("getInventory", localVarResponse); + } + return new ApiResponse>( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference>() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -231,14 +244,18 @@ public class StoreApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("getOrderById", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("getOrderById", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -300,14 +317,18 @@ public class StoreApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("placeOrder", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("placeOrder", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java index 6afc9d06f6d..d4f06af3fd5 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/UserApi.java @@ -100,14 +100,23 @@ public class UserApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("createUser", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("createUser", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -172,14 +181,23 @@ public class UserApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("createUsersWithArrayInput", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("createUsersWithArrayInput", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -244,14 +262,23 @@ public class UserApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("createUsersWithListInput", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("createUsersWithListInput", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -316,14 +343,23 @@ public class UserApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("deleteUser", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("deleteUser", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -385,14 +421,18 @@ public class UserApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("getUserByName", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("getUserByName", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -456,14 +496,18 @@ public class UserApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("loginUser", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("loginUser", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), - memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) + memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } } catch (IOException e) { throw new ApiException(e); } @@ -534,14 +578,23 @@ public class UserApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("logoutUser", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("logoutUser", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } @@ -598,14 +651,23 @@ public class UserApi { if (memberVarResponseInterceptor != null) { memberVarResponseInterceptor.accept(localVarResponse); } - if (localVarResponse.statusCode()/ 100 != 2) { - throw getApiException("updateUser", localVarResponse); - } - return new ApiResponse( + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("updateUser", localVarResponse); + } + return new ApiResponse( localVarResponse.statusCode(), localVarResponse.headers().map(), + null ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } } catch (IOException e) { throw new ApiException(e); } From 8e303150ae18e89c70ca4c17c90d41f522ba2773 Mon Sep 17 00:00:00 2001 From: Berlin Cho Date: Thu, 25 Nov 2021 16:12:55 +0800 Subject: [PATCH 27/61] [Java][resttemplate] Support URL queryParams Comma encoding (#10958) * Java Encode comma (with unit tests) * fix PMD warnings --- .../libraries/resttemplate/ApiClient.mustache | 41 ++++++++++++------- .../org/openapitools/client/ApiClient.java | 41 ++++++++++++------- .../openapitools/client/ApiClientTest.java | 31 ++++++++++++++ .../org/openapitools/client/ApiClient.java | 41 ++++++++++++------- .../openapitools/client/ApiClientTest.java | 31 ++++++++++++++ 5 files changed, 143 insertions(+), 42 deletions(-) create mode 100644 samples/client/petstore/java/resttemplate-withXml/src/test/java/org/openapitools/client/ApiClientTest.java create mode 100644 samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache index e48370f1539..f868eaa6dbf 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache @@ -34,6 +34,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.web.util.DefaultUriBuilderFactory; {{#threetenbp}} import org.threeten.bp.*; import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; @@ -622,6 +623,12 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { * @return path with placeholders replaced by variables */ public String expandPath(String pathTemplate, Map variables) { + // disable default URL encoding + DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(); + uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); + final RestTemplate restTemplate = new RestTemplate(); + restTemplate.setUriTemplateHandler(uriBuilderFactory); + return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString(); } @@ -632,27 +639,33 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { * @param uriParams The path parameters * return templatized query string */ - private String generateQueryUri(MultiValueMap queryParams, Map uriParams) { + public String generateQueryUri(MultiValueMap queryParams, Map uriParams) { StringBuilder queryBuilder = new StringBuilder(); queryParams.forEach((name, values) -> { - if (CollectionUtils.isEmpty(values)) { - if (queryBuilder.length() != 0) { - queryBuilder.append('&'); - } - queryBuilder.append(name); - } else { - int valueItemCounter = 0; - for (Object value : values) { + try { + final String encodedName = URLEncoder.encode(name.toString(), "UTF-8"); + if (CollectionUtils.isEmpty(values)) { if (queryBuilder.length() != 0) { queryBuilder.append('&'); } - queryBuilder.append(name); - if (value != null) { - String templatizedKey = name + valueItemCounter++; - uriParams.put(templatizedKey, value.toString()); - queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + queryBuilder.append(encodedName); + } else { + int valueItemCounter = 0; + for (Object value : values) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(encodedName); + if (value != null) { + String templatizedKey = encodedName + valueItemCounter++; + final String encodedValue = URLEncoder.encode(value.toString(), "UTF-8"); + uriParams.put(templatizedKey, encodedValue); + queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + } } } + } catch (UnsupportedEncodingException e) { + } }); return queryBuilder.toString(); diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java index 093e4897144..8e5e2933cec 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java @@ -30,6 +30,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.web.util.DefaultUriBuilderFactory; import org.threeten.bp.*; import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; import org.springframework.http.converter.HttpMessageConverter; @@ -578,6 +579,12 @@ public class ApiClient extends JavaTimeFormatter { * @return path with placeholders replaced by variables */ public String expandPath(String pathTemplate, Map variables) { + // disable default URL encoding + DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(); + uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); + final RestTemplate restTemplate = new RestTemplate(); + restTemplate.setUriTemplateHandler(uriBuilderFactory); + return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString(); } @@ -588,27 +595,33 @@ public class ApiClient extends JavaTimeFormatter { * @param uriParams The path parameters * return templatized query string */ - private String generateQueryUri(MultiValueMap queryParams, Map uriParams) { + public String generateQueryUri(MultiValueMap queryParams, Map uriParams) { StringBuilder queryBuilder = new StringBuilder(); queryParams.forEach((name, values) -> { - if (CollectionUtils.isEmpty(values)) { - if (queryBuilder.length() != 0) { - queryBuilder.append('&'); - } - queryBuilder.append(name); - } else { - int valueItemCounter = 0; - for (Object value : values) { + try { + final String encodedName = URLEncoder.encode(name.toString(), "UTF-8"); + if (CollectionUtils.isEmpty(values)) { if (queryBuilder.length() != 0) { queryBuilder.append('&'); } - queryBuilder.append(name); - if (value != null) { - String templatizedKey = name + valueItemCounter++; - uriParams.put(templatizedKey, value.toString()); - queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + queryBuilder.append(encodedName); + } else { + int valueItemCounter = 0; + for (Object value : values) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(encodedName); + if (value != null) { + String templatizedKey = encodedName + valueItemCounter++; + final String encodedValue = URLEncoder.encode(value.toString(), "UTF-8"); + uriParams.put(templatizedKey, encodedValue); + queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + } } } + } catch (UnsupportedEncodingException e) { + } }); return queryBuilder.toString(); diff --git a/samples/client/petstore/java/resttemplate-withXml/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/resttemplate-withXml/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 00000000000..4b3a63c3e26 --- /dev/null +++ b/samples/client/petstore/java/resttemplate-withXml/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,31 @@ +package org.openapitools.client; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import java.util.*; +import org.junit.*; +import org.springframework.util.MultiValueMap; +import org.springframework.util.LinkedMultiValueMap; + +public class ApiClientTest { + ApiClient apiClient; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + /** + * Test uri encoding when params contains comma + */ + @Test + public void testUriEncoderWithComma() { + Map uriParams = new HashMap<>(); + MultiValueMap queryParams = new LinkedMultiValueMap(); + queryParams.add("key", "val,comma"); + apiClient.generateQueryUri(queryParams, uriParams); + + assertEquals("/key=val%2Ccomma", apiClient.expandPath("/key={key0}", uriParams)); + } +} \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java index 89f43f67cc1..42d81a59578 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java @@ -25,6 +25,7 @@ import org.springframework.util.StringUtils; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.web.util.DefaultUriBuilderFactory; import org.threeten.bp.*; import com.fasterxml.jackson.datatype.threetenbp.ThreeTenModule; import org.springframework.http.converter.HttpMessageConverter; @@ -573,6 +574,12 @@ public class ApiClient extends JavaTimeFormatter { * @return path with placeholders replaced by variables */ public String expandPath(String pathTemplate, Map variables) { + // disable default URL encoding + DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(); + uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.NONE); + final RestTemplate restTemplate = new RestTemplate(); + restTemplate.setUriTemplateHandler(uriBuilderFactory); + return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString(); } @@ -583,27 +590,33 @@ public class ApiClient extends JavaTimeFormatter { * @param uriParams The path parameters * return templatized query string */ - private String generateQueryUri(MultiValueMap queryParams, Map uriParams) { + public String generateQueryUri(MultiValueMap queryParams, Map uriParams) { StringBuilder queryBuilder = new StringBuilder(); queryParams.forEach((name, values) -> { - if (CollectionUtils.isEmpty(values)) { - if (queryBuilder.length() != 0) { - queryBuilder.append('&'); - } - queryBuilder.append(name); - } else { - int valueItemCounter = 0; - for (Object value : values) { + try { + final String encodedName = URLEncoder.encode(name.toString(), "UTF-8"); + if (CollectionUtils.isEmpty(values)) { if (queryBuilder.length() != 0) { queryBuilder.append('&'); } - queryBuilder.append(name); - if (value != null) { - String templatizedKey = name + valueItemCounter++; - uriParams.put(templatizedKey, value.toString()); - queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + queryBuilder.append(encodedName); + } else { + int valueItemCounter = 0; + for (Object value : values) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(encodedName); + if (value != null) { + String templatizedKey = encodedName + valueItemCounter++; + final String encodedValue = URLEncoder.encode(value.toString(), "UTF-8"); + uriParams.put(templatizedKey, encodedValue); + queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + } } } + } catch (UnsupportedEncodingException e) { + } }); return queryBuilder.toString(); diff --git a/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 00000000000..4b3a63c3e26 --- /dev/null +++ b/samples/client/petstore/java/resttemplate/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,31 @@ +package org.openapitools.client; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import java.util.*; +import org.junit.*; +import org.springframework.util.MultiValueMap; +import org.springframework.util.LinkedMultiValueMap; + +public class ApiClientTest { + ApiClient apiClient; + + @Before + public void setup() { + apiClient = new ApiClient(); + } + + /** + * Test uri encoding when params contains comma + */ + @Test + public void testUriEncoderWithComma() { + Map uriParams = new HashMap<>(); + MultiValueMap queryParams = new LinkedMultiValueMap(); + queryParams.add("key", "val,comma"); + apiClient.generateQueryUri(queryParams, uriParams); + + assertEquals("/key=val%2Ccomma", apiClient.expandPath("/key={key0}", uriParams)); + } +} \ No newline at end of file From a620853216ff7fb6848760bf559aff2db1cf946f Mon Sep 17 00:00:00 2001 From: Fumito Nakazawa Date: Fri, 26 Nov 2021 01:55:06 +0900 Subject: [PATCH 28/61] [swift5] Refactor encodeToJSON (#10961) * Add protocol extension method * execute sample script * Add Packing.cmake * Revert "Add Packing.cmake" This reverts commit cb52547fe34c5d17dd83267daa259b7ee3ddd503. * Remove empty lines * Revert FILES * Add Packing.cmake --- .../main/resources/swift5/Extensions.mustache | 48 ++++--------------- .../src/main/resources/swift5/Models.mustache | 4 ++ samples/client/petstore/c/Packing.cmake | 24 ++++++++++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ .../Sources/PetstoreClient/Extensions.swift | 48 ++++--------------- .../Sources/PetstoreClient/Models.swift | 4 ++ .../Classes/OpenAPIs/Extensions.swift | 48 ++++--------------- .../Classes/OpenAPIs/Models.swift | 4 ++ 31 files changed, 219 insertions(+), 585 deletions(-) create mode 100644 samples/client/petstore/c/Packing.cmake diff --git a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache index b286fa9f42a..eb3fd11eb8e 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Extensions.mustache @@ -11,33 +11,15 @@ import AnyCodable import PromiseKit{{/usePromiseKit}}{{#useVapor}} import Vapor{{/useVapor}}{{^useVapor}} -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { func encodeToJSON() -> Any { return CodableHelper.dateFormatter.string(from: self) } -} - -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } }{{/useVapor}}{{#generateModelAdditionalProperties}} extension String: CodingKey { diff --git a/modules/openapi-generator/src/main/resources/swift5/Models.mustache b/modules/openapi-generator/src/main/resources/swift5/Models.mustache index e8ca64cdc52..3b2c5eafce1 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Models.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Models.mustache @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/c/Packing.cmake b/samples/client/petstore/c/Packing.cmake new file mode 100644 index 00000000000..15bd4c8d5e9 --- /dev/null +++ b/samples/client/petstore/c/Packing.cmake @@ -0,0 +1,24 @@ +set(CPACK_PACKAGE_NAME lib${pkgName}) + +set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) +set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) +set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) + +set(CPACK_PACKAGE_DESCRIPTION_SUMMARY ${PROJECT_PACKAGE_DESCRIPTION_SUMMARY}) +set(CPACK_PACKAGE_VENDOR ${PROJECT_PACKAGE_VENDOR}) +set(CPACK_PACKAGE_CONTACT ${PROJECT_PACKAGE_CONTACT}) +set(CPACK_DEBIAN_PACKAGE_MAINTAINER ${PROJECT_PACKAGE_MAINTAINER}) + +set(CPACK_VERBATIM_VARIABLES YES) + +set(CPACK_PACKAGE_INSTALL_DIRECTORY ${CPACK_PACKAGE_NAME}) + +set(CPACK_PACKAGING_INSTALL_PREFIX ${CMAKE_INSTALL_PREFIX}) + +set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT) + +set(CPACK_DEB_COMPONENT_INSTALL YES) + +set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS TRUE) + +include(CPack) \ No newline at end of file diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 63647fe3703..255ab49db7b 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift index 5db24390bd7..0c1c7548898 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + internal enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 2c1ceeb385b..cc93d4c30d3 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -10,33 +10,15 @@ import AnyCodable #endif import PromiseKit -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -84,18 +66,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 4077c82552a..570ea5f64bd 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension HTTPURLResponse { var isStatusCodeSuccessful: Bool { return (200 ..< 300).contains(statusCode) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift index 5831422f09d..e2b73073804 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -9,33 +9,15 @@ import Foundation import AnyCodable #endif -extension Bool: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Float: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension Int32: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int32) } -} - -extension Int64: JSONEncodable { - func encodeToJSON() -> Any { return NSNumber(value: self as Int64) } -} - -extension Double: JSONEncodable { - func encodeToJSON() -> Any { return self } -} - -extension String: JSONEncodable { - func encodeToJSON() -> Any { return self } -} +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} extension RawRepresentable where RawValue: JSONEncodable { func encodeToJSON() -> Any { return self.rawValue } @@ -83,18 +65,6 @@ extension Date: JSONEncodable { } } -extension URL: JSONEncodable { - func encodeToJSON() -> Any { - return self - } -} - -extension UUID: JSONEncodable { - func encodeToJSON() -> Any { - return self.uuidString - } -} - extension String: CodingKey { public var stringValue: String { diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift index e5802990167..ab4165a9b45 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -10,6 +10,10 @@ protocol JSONEncodable { func encodeToJSON() -> Any } +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } From 06faa289bd93c5fe1f2caa376e32ec6cc07627a2 Mon Sep 17 00:00:00 2001 From: Justin Black Date: Thu, 25 Nov 2021 18:00:53 -0800 Subject: [PATCH 29/61] Adds codegenParameter.schema to allow referenced schemas in parameters (#10934) * Removes python-experimental folder * Sets schema in fromParameter * Sets schema in codegenParameter * Adds tests of schema --- .../org/openapitools/codegen/CodegenParameter.java | 13 ++++++++++++- .../org/openapitools/codegen/DefaultCodegen.java | 2 ++ .../openapitools/codegen/DefaultCodegenTest.java | 4 ++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index 38eb785410e..5bd8a369f0d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -52,6 +52,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { public boolean hasValidation; public boolean isNullable; public boolean isDeprecated; + private CodegenProperty schema; /** * Determines whether this parameter is mandatory. If the parameter is in "path", * this property is required and its value MUST be true. Otherwise, the property @@ -162,6 +163,9 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { output.setHasDiscriminatorWithNonEmptyMapping(this.hasDiscriminatorWithNonEmptyMapping); output.setHasMultipleTypes(this.hasMultipleTypes); + if (this.schema != null) { + output.setSchema(this.schema); + } if (this.composedSchemas != null) { output.setComposedSchemas(this.getComposedSchemas()); } @@ -222,7 +226,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { @Override public int hashCode() { - return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, isAllowEmptyValue, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes); + return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, isAllowEmptyValue, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema); } @Override @@ -278,6 +282,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { getExclusiveMaximum() == that.getExclusiveMaximum() && getExclusiveMinimum() == that.getExclusiveMinimum() && getUniqueItems() == that.getUniqueItems() && + Objects.equals(schema, that.getSchema()) && Objects.equals(composedSchemas, that.getComposedSchemas()) && Objects.equals(baseName, that.baseName) && Objects.equals(paramName, that.paramName) && @@ -403,6 +408,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { sb.append(", getHasDiscriminatorWithNonEmptyMapping=").append(hasDiscriminatorWithNonEmptyMapping); sb.append(", composedSchemas=").append(composedSchemas); sb.append(", hasMultipleTypes=").append(hasMultipleTypes); + sb.append(", schema=").append(schema); sb.append('}'); return sb.toString(); } @@ -732,5 +738,10 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { @Override public void setHasMultipleTypes(boolean hasMultipleTypes) { this.hasMultipleTypes = hasMultipleTypes; } + + public CodegenProperty getSchema() {return schema; } + + public void setSchema(CodegenProperty schema) { this.schema = schema; } + } 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 6e669ab37cd..563dc10ebc9 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 @@ -4499,6 +4499,8 @@ public class DefaultCodegen implements CodegenConfig { Schema parameterSchema; if (parameter.getSchema() != null) { parameterSchema = parameter.getSchema(); + CodegenProperty prop = fromProperty(parameter.getName(), parameterSchema); + codegenParameter.setSchema(prop); } else if (parameter.getContent() != null) { Content content = parameter.getContent(); if (content.size() > 1) { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index 7afce7c4391..aaede097e3d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -222,6 +222,7 @@ public class DefaultCodegenTest { CodegenParameter codegenParameter = codegen.fromFormProperty("enum_form_string", (Schema) requestBodySchema.getProperties().get("enum_form_string"), new HashSet()); Assert.assertEquals(codegenParameter.defaultValue, "-efg"); + Assert.assertEquals(codegenParameter.getSchema(), null); } @Test @@ -2035,6 +2036,9 @@ public class DefaultCodegenTest { Assert.assertEquals(parameter.dataType, "PageQuery1"); Assert.assertEquals(imports.size(), 1); Assert.assertEquals(imports.iterator().next(), "PageQuery1"); + + Assert.assertNotNull(parameter.getSchema()); + Assert.assertEquals(parameter.getSchema().baseType, "object"); } @Test From 3d92df5a4173384b3e3f35a447dfd7782f112473 Mon Sep 17 00:00:00 2001 From: Kevin Chen Date: Fri, 26 Nov 2021 01:04:19 -0600 Subject: [PATCH 30/61] [Java][okhttp-gson] Support text/plain body (#10885) * support serialize RequestBody with contentType text/plain * add Serialize test * update test comment --- .../libraries/okhttp-gson/ApiClient.mustache | 2 ++ .../org/openapitools/client/ApiClient.java | 2 ++ .../org/openapitools/client/ApiClient.java | 2 ++ .../org/openapitools/client/ApiClient.java | 2 ++ .../org/openapitools/client/ApiClient.java | 2 ++ .../org/openapitools/client/ApiClientTest.java | 18 ++++++++++++++++++ 6 files changed, 28 insertions(+) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index a0c3c4e5b7c..421b7782ebe 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -1081,6 +1081,8 @@ public class ApiClient { } else if (obj instanceof File) { // File body parameter support. return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if ("text/plain".equals(contentType) && obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); } else if (isJsonMime(contentType)) { String content; if (obj != null) { diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java index 843d13b69a1..f2fca9d7ea3 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java @@ -871,6 +871,8 @@ public class ApiClient { } else if (obj instanceof File) { // File body parameter support. return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if ("text/plain".equals(contentType) && obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); } else if (isJsonMime(contentType)) { String content; if (obj != null) { diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java index 69d6469c85a..ddd9a420bb6 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java @@ -972,6 +972,8 @@ public class ApiClient { } else if (obj instanceof File) { // File body parameter support. return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if ("text/plain".equals(contentType) && obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); } else if (isJsonMime(contentType)) { String content; if (obj != null) { diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java index 7ef420e3c7c..93328801c2e 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java @@ -973,6 +973,8 @@ public class ApiClient { } else if (obj instanceof File) { // File body parameter support. return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if ("text/plain".equals(contentType) && obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); } else if (isJsonMime(contentType)) { String content; if (obj != null) { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java index 7ef420e3c7c..93328801c2e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java @@ -973,6 +973,8 @@ public class ApiClient { } else if (obj instanceof File) { // File body parameter support. return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if ("text/plain".equals(contentType) && obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); } else if (isJsonMime(contentType)) { String content; if (obj != null) { diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java index 9edd0ae7bed..9daf2dcf886 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java @@ -342,4 +342,22 @@ public class ApiClientTest { public void testNullHttpClient() { apiClient.setHttpClient(null); } + + /** + * Tests the ApiClient serialize methods + */ + @Test + public void testSerializeRequest() throws ApiException { + assertNotNull(apiClient.serialize("test", "text/plain")); + assertNotNull(apiClient.serialize("{}", "application/json")); + } + + /** + * Tests the ApiClient serialize methods with unsupported content-type + * should raise ApiException + */ + @Test(expected = ApiException.class) + public void testUnsupportedSerializeRequest() throws ApiException { + apiClient.serialize("test", "unsupported/type"); + } } From 309b67f91e182bdf0d80d53f8564e69232f3ebd8 Mon Sep 17 00:00:00 2001 From: sullis Date: Thu, 25 Nov 2021 23:05:47 -0800 Subject: [PATCH 31/61] update GitHub Actions (#10963) - use setup-java v2 everywhere - use Temurin JDK everywhere --- .../workflows/check-supported-versions.yaml | 2 +- .github/workflows/gradle-test.yaml | 2 +- .github/workflows/openapi-generator.yaml | 18 ++++++++++++------ .github/workflows/samples-dart.yaml | 4 ++-- .github/workflows/samples-kotlin.yaml | 2 +- .github/workflows/sonar.yml | 2 +- 6 files changed, 18 insertions(+), 12 deletions(-) diff --git a/.github/workflows/check-supported-versions.yaml b/.github/workflows/check-supported-versions.yaml index ba496f3ab5c..017b4bdf0ab 100644 --- a/.github/workflows/check-supported-versions.yaml +++ b/.github/workflows/check-supported-versions.yaml @@ -26,7 +26,7 @@ jobs: - name: Set up JDK ${{ matrix.java }} uses: actions/setup-java@v2 with: - distribution: 'adopt' + distribution: 'temurin' java-version: ${{ matrix.java }} - uses: actions/cache@v2.1.7 diff --git a/.github/workflows/gradle-test.yaml b/.github/workflows/gradle-test.yaml index 6be454c68a6..c6f6f495ab1 100644 --- a/.github/workflows/gradle-test.yaml +++ b/.github/workflows/gradle-test.yaml @@ -36,7 +36,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-java@v2 with: - distribution: 'adopt' + distribution: 'temurin' java-version: 11 # Cache Gradle Dependencies - name: Setup Gradle Dependencies Cache diff --git a/.github/workflows/openapi-generator.yaml b/.github/workflows/openapi-generator.yaml index a5defde9826..b2e477592d4 100644 --- a/.github/workflows/openapi-generator.yaml +++ b/.github/workflows/openapi-generator.yaml @@ -17,9 +17,10 @@ jobs: steps: - uses: actions/checkout@v2 - name: Set up JDK 8 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: java-version: 8 + distribution: 'temurin' - name: Cache maven dependencies uses: actions/cache@v2.1.7 env: @@ -52,9 +53,10 @@ jobs: steps: - uses: actions/checkout@v2 - name: Set up JDK 8 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: java-version: 8 + distribution: 'temurin' - name: Cache maven dependencies uses: actions/cache@v2.1.7 env: @@ -86,9 +88,10 @@ jobs: steps: - uses: actions/checkout@v2 - name: Set up JDK 8 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: java-version: 8 + distribution: 'temurin' - name: Download openapi-generator-cli.jar artifact uses: actions/download-artifact@v2.0.10 with: @@ -124,9 +127,10 @@ jobs: steps: - uses: actions/checkout@v2 - name: Set up JDK 8 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: java-version: 8 + distribution: 'temurin' - name: Download openapi-generator-cli.jar artifact uses: actions/download-artifact@v2.0.10 with: @@ -158,9 +162,10 @@ jobs: steps: - uses: actions/checkout@v2 - name: Set up JDK 11 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: java-version: 11 + distribution: 'temurin' - name: Cache maven dependencies uses: actions/cache@v2.1.7 env: @@ -190,9 +195,10 @@ jobs: steps: - uses: actions/checkout@v2 - name: Set up JDK 11 - uses: actions/setup-java@v1 + uses: actions/setup-java@v2 with: java-version: 11 + distribution: 'temurin' - name: Cache maven dependencies uses: actions/cache@v2.1.7 env: diff --git a/.github/workflows/samples-dart.yaml b/.github/workflows/samples-dart.yaml index e4c94f3f125..5efe3b6b686 100644 --- a/.github/workflows/samples-dart.yaml +++ b/.github/workflows/samples-dart.yaml @@ -20,7 +20,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-java@v2 with: - distribution: 'adopt' + distribution: 'temurin' java-version: 8 - name: Cache maven dependencies uses: actions/cache@v2.1.7 @@ -53,7 +53,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-java@v2 with: - distribution: 'adopt' + distribution: 'temurin' java-version: 8 - name: Cache maven dependencies uses: actions/cache@v2.1.7 diff --git a/.github/workflows/samples-kotlin.yaml b/.github/workflows/samples-kotlin.yaml index 39a7ea7c957..c6f6f3745c0 100644 --- a/.github/workflows/samples-kotlin.yaml +++ b/.github/workflows/samples-kotlin.yaml @@ -45,7 +45,7 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-java@v2 with: - distribution: 'adopt' + distribution: 'temurin' java-version: 8 - name: Cache maven dependencies uses: actions/cache@v2.1.7 diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index d991e052a7d..63f622d66e1 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -16,7 +16,7 @@ jobs: - name: Set up JDK 11 uses: actions/setup-java@v2 with: - distribution: 'adopt' + distribution: 'temurin' java-version: 11 - name: Compile with Maven run: mvn -B -q clean install jacoco:report From ae911ff2c1902ce91e3e3e0056b33a33e4365eac Mon Sep 17 00:00:00 2001 From: Tal Kirshboim Date: Sat, 27 Nov 2021 02:36:19 +0100 Subject: [PATCH 32/61] Support generated gradle module as child module (#10966) --- docs/generators/kotlin.md | 1 + .../openapitools/codegen/languages/KotlinClientCodegen.java | 2 ++ .../libraries/multiplatform/build.gradle.kts.mustache | 4 ++-- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md index fca84164c69..49e02994b74 100644 --- a/docs/generators/kotlin.md +++ b/docs/generators/kotlin.md @@ -17,6 +17,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |library|Library template (sub-template) to use|
    **jvm-okhttp4**
    [DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.
    **jvm-okhttp3**
    Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0.
    **jvm-retrofit2**
    Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.
    **multiplatform**
    Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.0. JSON processing: Kotlinx Serialization: 1.2.1.
    |jvm-okhttp4| |modelMutable|Create mutable models| |false| |moshiCodeGen|Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.| |false| +|omitGradlePluginVersions|Whether to declare Gradle plugin versions in build files.| |false| |packageName|Generated artifact package name.| |org.openapitools.client| |parcelizeModels|toggle "@Parcelize" for generated models| |null| |requestDateConverter|JVM-Option. Defines in how to handle date-time objects that are used for a request (as query or parameter)|
    **toJson**
    [DEFAULT] Date formatter option using a json converter.
    **toString**
    Use the 'toString'-method of the date-time object to retrieve the related string representation.
    |toJson| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java index 91e3ce32c3f..28a3853332d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java @@ -49,6 +49,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { public static final String USE_RX_JAVA3 = "useRxJava3"; public static final String USE_COROUTINES = "useCoroutines"; public static final String DO_NOT_USE_RX_AND_COROUTINES = "doNotUseRxAndCoroutines"; + public static final String OMIT_GRADLE_PLUGIN_VERSIONS = "omitGradlePluginVersions"; public static final String DATE_LIBRARY = "dateLibrary"; public static final String REQUEST_DATE_CONVERTER = "requestDateConverter"; @@ -201,6 +202,7 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { cliOptions.add(CliOption.newBoolean(USE_RX_JAVA2, "Whether to use the RxJava2 adapter with the retrofit2 library. IMPORTANT: this option has been deprecated. Please use `useRxJava3` instead.")); cliOptions.add(CliOption.newBoolean(USE_RX_JAVA3, "Whether to use the RxJava3 adapter with the retrofit2 library.")); cliOptions.add(CliOption.newBoolean(USE_COROUTINES, "Whether to use the Coroutines adapter with the retrofit2 library.")); + cliOptions.add(CliOption.newBoolean(OMIT_GRADLE_PLUGIN_VERSIONS, "Whether to declare Gradle plugin versions in build files.")); cliOptions.add(CliOption.newBoolean(MOSHI_CODE_GEN, "Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.")); diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache index ac4f19048a1..2a620721ba4 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache @@ -1,8 +1,8 @@ import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget plugins { - kotlin("multiplatform") version "1.5.31" // kotlin_version - kotlin("plugin.serialization") version "1.5.31" // kotlin_version + kotlin("multiplatform"){{^omitGradlePluginVersions}} version "1.5.31" // kotlin_version{{/omitGradlePluginVersions}} + kotlin("plugin.serialization"){{^omitGradlePluginVersions}} version "1.5.31" // kotlin_version{{/omitGradlePluginVersions}} } group = "{{groupId}}" From b7e7c13673bd20de9b605a4e310cfcde607b84fe Mon Sep 17 00:00:00 2001 From: Takayuki Matsubara Date: Sat, 27 Nov 2021 11:02:14 +0900 Subject: [PATCH 33/61] update ruby's default options on document (#10924) --- docs/generators/ruby.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/generators/ruby.md b/docs/generators/ruby.md index c9e0477e967..5cd52c8c27a 100644 --- a/docs/generators/ruby.md +++ b/docs/generators/ruby.md @@ -10,13 +10,13 @@ These options may be applied as additional-properties (cli) or configOptions (pl |allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| -|gemAuthor|gem author (only one is supported).| |null| +|gemAuthor|gem author (only one is supported).| |OpenAPI-Generator| |gemAuthorEmail|gem author email (only one is supported).| |null| |gemDescription|gem description. | |This gem maps to a REST API| -|gemHomepage|gem homepage. | |http://org.openapitools| +|gemHomepage|gem homepage. | |https://openapi-generator.tech| |gemLicense|gem license. | |unlicense| |gemName|gem name (convention: underscore_case).| |openapi_client| -|gemRequiredRubyVersion|gem required Ruby version. | |>= 1.9| +|gemRequiredRubyVersion|gem required Ruby version. | |>= 2.4| |gemSummary|gem summary. | |A ruby wrapper for the REST APIs| |gemVersion|gem version.| |1.0.0| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| From 3b5345eb57280340a606cde9a8eb9d25bfec03b1 Mon Sep 17 00:00:00 2001 From: WILLIAM CHENG Date: Sat, 27 Nov 2021 10:03:03 +0800 Subject: [PATCH 34/61] update option value in ruby generator --- .../openapitools/codegen/languages/RubyClientCodegen.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java index f7d5a20e079..335a329ef59 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java @@ -141,10 +141,10 @@ public class RubyClientCodegen extends AbstractRubyCodegen { defaultValue("unlicense")); cliOptions.add(new CliOption(GEM_REQUIRED_RUBY_VERSION, "gem required Ruby version. "). - defaultValue(">= 1.9")); + defaultValue(">= 2.4")); cliOptions.add(new CliOption(GEM_HOMEPAGE, "gem homepage. "). - defaultValue("http://org.openapitools")); + defaultValue("https://openapi-generator.tech")); cliOptions.add(new CliOption(GEM_SUMMARY, "gem summary. "). defaultValue("A ruby wrapper for the REST APIs")); @@ -152,7 +152,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { cliOptions.add(new CliOption(GEM_DESCRIPTION, "gem description. "). defaultValue("This gem maps to a REST API")); - cliOptions.add(new CliOption(GEM_AUTHOR, "gem author (only one is supported).")); + cliOptions.add(new CliOption(GEM_AUTHOR, "gem author (only one is supported).").defaultValue("OpenAPI-Generator")); cliOptions.add(new CliOption(GEM_AUTHOR_EMAIL, "gem author email (only one is supported).")); From 8e2e200e18f746805712d5629edceee159ba4abc Mon Sep 17 00:00:00 2001 From: Alexander Karkossa Date: Mon, 29 Nov 2021 17:42:22 +0100 Subject: [PATCH 35/61] fix: changed Any to kotlin.Any (#10985) --- .../src/main/resources/kotlin-client/enum_class.mustache | 4 ++-- .../src/main/kotlin/org/openapitools/client/models/PetEnum.kt | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache index 57b1e5f1272..fcdcd87ffa9 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/enum_class.mustache @@ -67,12 +67,12 @@ import kotlinx.serialization.* /** * Converts the provided [data] to a [String] on success, null otherwise. */ - fun encode(data: Any?): kotlin.String? = if (data is {{classname}}) "$data" else null + fun encode(data: kotlin.Any?): kotlin.String? = if (data is {{classname}}) "$data" else null /** * Returns a valid [{{classname}}] for [data], null otherwise. */ - fun decode(data: Any?): {{classname}}? = data?.let { + fun decode(data: kotlin.Any?): {{classname}}? = data?.let { val normalizedData = "$it".lowercase() values().firstOrNull { value -> it == value || normalizedData == "$value".lowercase() diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt index aa6831225a2..4d9fa1abd64 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/models/PetEnum.kt @@ -50,12 +50,12 @@ enum class PetEnum(val value: kotlin.String) { /** * Converts the provided [data] to a [String] on success, null otherwise. */ - fun encode(data: Any?): kotlin.String? = if (data is PetEnum) "$data" else null + fun encode(data: kotlin.Any?): kotlin.String? = if (data is PetEnum) "$data" else null /** * Returns a valid [PetEnum] for [data], null otherwise. */ - fun decode(data: Any?): PetEnum? = data?.let { + fun decode(data: kotlin.Any?): PetEnum? = data?.let { val normalizedData = "$it".lowercase() values().firstOrNull { value -> it == value || normalizedData == "$value".lowercase() From 8702f24f05dfa561ad3cb4cdfa4d0d5d6f7c2abf Mon Sep 17 00:00:00 2001 From: Justin Black Date: Mon, 29 Nov 2021 09:31:38 -0800 Subject: [PATCH 36/61] Adds request body content data to allow multiple content types to be sent to servers (#10973) * Adds CodegenMediaType and CodegenEncoding * Adds partial new code to set Parameter content data * Adds content to CodegenParameter * Sets content for request bodies * Adds testParameterContent * Adds testRequestBodyContent --- .../openapitools/codegen/CodegenEncoding.java | 67 +++++++++++++++ .../codegen/CodegenMediaType.java | 45 ++++++++++ .../codegen/CodegenParameter.java | 15 +++- .../openapitools/codegen/DefaultCodegen.java | 57 +++++++++++++ .../codegen/DefaultCodegenTest.java | 72 ++++++++++++++++ .../src/test/resources/3_0/content-data.yaml | 83 +++++++++++++++++++ .../src/openapi_server/openapi/openapi.yaml | 13 +++ .../openapi_server/openapi/openapi.yaml | 13 +++ .../petstore/python-fastapi/openapi.yaml | 8 ++ .../openapi_server/openapi/openapi.yaml | 13 +++ 10 files changed, 385 insertions(+), 1 deletion(-) create mode 100644 modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenEncoding.java create mode 100644 modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenMediaType.java create mode 100644 modules/openapi-generator/src/test/resources/3_0/content-data.yaml diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenEncoding.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenEncoding.java new file mode 100644 index 00000000000..efd5b0f16ab --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenEncoding.java @@ -0,0 +1,67 @@ +package org.openapitools.codegen; + +import java.util.List; +import java.util.Objects; + +public class CodegenEncoding { + private String contentType; + private List headers; + private String style; + private boolean explode; + private boolean allowReserved; + + public CodegenEncoding(String contentType, List headers, String style, boolean explode, boolean allowReserved) { + this.contentType = contentType; + this.headers = headers; + this.style = style; + this.explode = explode; + this.allowReserved = allowReserved; + } + + public String getContentType() { + return contentType; + } + + public List getHeaders() { + return headers; + } + + public String getStyle() { + return style; + } + + public boolean getExplode() { + return explode; + } + + public boolean getAllowReserved() { + return allowReserved; + } + + public String toString() { + final StringBuilder sb = new StringBuilder("CodegenEncoding{"); + sb.append("contentType=").append(contentType); + sb.append(", headers=").append(headers); + sb.append(", style=").append(style); + sb.append(", explode=").append(explode); + sb.append(", allowReserved=").append(allowReserved); + sb.append('}'); + return sb.toString(); + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CodegenEncoding that = (CodegenEncoding) o; + return contentType == that.getContentType() && + Objects.equals(headers, that.getHeaders()) && + style == that.getStyle() && + explode == that.getExplode() && + allowReserved == that.getAllowReserved(); + } + + @Override + public int hashCode() { + return Objects.hash(contentType, headers, style, explode, allowReserved); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenMediaType.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenMediaType.java new file mode 100644 index 00000000000..965e5031942 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenMediaType.java @@ -0,0 +1,45 @@ +package org.openapitools.codegen; + +import java.util.LinkedHashMap; +import java.util.Objects; + +public class CodegenMediaType { + private CodegenProperty schema; + private LinkedHashMap encoding; + + public CodegenMediaType(CodegenProperty schema, LinkedHashMap encoding) { + this.schema = schema; + this.encoding = encoding; + } + + public CodegenProperty getSchema() { + return schema; + } + + public LinkedHashMap getEncoding() { + return encoding; + } + + public String toString() { + final StringBuilder sb = new StringBuilder("CodegenMediaType{"); + sb.append("schema=").append(schema); + sb.append(", encoding=").append(encoding); + sb.append('}'); + return sb.toString(); + } + + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + CodegenMediaType that = (CodegenMediaType) o; + return Objects.equals(schema,that.getSchema()) && + Objects.equals(encoding, that.getEncoding()); + } + + @Override + public int hashCode() { + return Objects.hash(schema, encoding); + } +} + + diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java index 5bd8a369f0d..dba1721fbca 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenParameter.java @@ -110,6 +110,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { private boolean hasDiscriminatorWithNonEmptyMapping; private CodegenComposedSchemas composedSchemas; private boolean hasMultipleTypes = false; + private LinkedHashMap content; public CodegenParameter copy() { CodegenParameter output = new CodegenParameter(); @@ -163,6 +164,9 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { output.setHasDiscriminatorWithNonEmptyMapping(this.hasDiscriminatorWithNonEmptyMapping); output.setHasMultipleTypes(this.hasMultipleTypes); + if (this.content != null) { + output.setContent(this.content); + } if (this.schema != null) { output.setSchema(this.schema); } @@ -226,7 +230,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { @Override public int hashCode() { - return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, isAllowEmptyValue, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema); + return Objects.hash(isFormParam, isQueryParam, isPathParam, isHeaderParam, isCookieParam, isBodyParam, isContainer, isCollectionFormatMulti, isPrimitiveType, isModel, isExplode, baseName, paramName, dataType, datatypeWithEnum, dataFormat, collectionFormat, description, unescapedDescription, baseType, defaultValue, enumName, style, isDeepObject, isAllowEmptyValue, example, jsonSchema, isString, isNumeric, isInteger, isLong, isNumber, isFloat, isDouble, isDecimal, isByteArray, isBinary, isBoolean, isDate, isDateTime, isUuid, isUri, isEmail, isFreeFormObject, isAnyType, isArray, isMap, isFile, isEnum, _enum, allowableValues, items, mostInnerItems, additionalProperties, vars, requiredVars, vendorExtensions, hasValidation, getMaxProperties(), getMinProperties(), isNullable, isDeprecated, required, getMaximum(), getExclusiveMaximum(), getMinimum(), getExclusiveMinimum(), getMaxLength(), getMinLength(), getPattern(), getMaxItems(), getMinItems(), getUniqueItems(), contentType, multipleOf, isNull, additionalPropertiesIsAnyType, hasVars, hasRequired, isShort, isUnboundedInteger, hasDiscriminatorWithNonEmptyMapping, composedSchemas, hasMultipleTypes, schema, content); } @Override @@ -282,6 +286,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { getExclusiveMaximum() == that.getExclusiveMaximum() && getExclusiveMinimum() == that.getExclusiveMinimum() && getUniqueItems() == that.getUniqueItems() && + Objects.equals(content, that.getContent()) && Objects.equals(schema, that.getSchema()) && Objects.equals(composedSchemas, that.getComposedSchemas()) && Objects.equals(baseName, that.baseName) && @@ -409,6 +414,7 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { sb.append(", composedSchemas=").append(composedSchemas); sb.append(", hasMultipleTypes=").append(hasMultipleTypes); sb.append(", schema=").append(schema); + sb.append(", content=").append(content); sb.append('}'); return sb.toString(); } @@ -743,5 +749,12 @@ public class CodegenParameter implements IJsonSchemaValidationProperties { public void setSchema(CodegenProperty schema) { this.schema = schema; } + public LinkedHashMap getContent() { + return content; + } + + public void setContent(LinkedHashMap content) { + this.content = content; + } } 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 563dc10ebc9..046d8609d3c 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 @@ -4486,6 +4486,7 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.isDeprecated = parameter.getDeprecated(); } codegenParameter.jsonSchema = Json.pretty(parameter); + codegenParameter.setContent(getContent(parameter.getContent(), imports)); if (GlobalSettings.getProperty("debugParser") != null) { LOGGER.info("working on Parameter {}", parameter.getName()); @@ -6557,6 +6558,61 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.pattern = toRegularExpression(schema.getPattern()); } + protected LinkedHashMap getContent(Content content, Set imports) { + if (content == null) { + return null; + } + LinkedHashMap cmtContent = new LinkedHashMap<>(); + for (Entry contentEntry: content.entrySet()) { + MediaType mt = contentEntry.getValue(); + LinkedHashMap ceMap = null; + if (mt.getEncoding() != null ) { + ceMap = new LinkedHashMap<>(); + Map encMap = mt.getEncoding(); + for (Entry encodingEntry: encMap.entrySet()) { + Encoding enc = encodingEntry.getValue(); + List headers = new ArrayList<>(); + if (enc.getHeaders() != null) { + Map encHeaders = enc.getHeaders(); + for (Entry headerEntry: encHeaders.entrySet()) { + String headerName = headerEntry.getKey(); + Header header = ModelUtils.getReferencedHeader(this.openAPI, headerEntry.getValue()); + Parameter headerParam = new Parameter(); + headerParam.setName(headerName); + headerParam.setIn("header"); + headerParam.setDescription(header.getDescription()); + headerParam.setRequired(header.getRequired()); + headerParam.setDeprecated(header.getDeprecated()); + headerParam.setStyle(Parameter.StyleEnum.valueOf(header.getStyle().name())); + headerParam.setExplode(header.getExplode()); + headerParam.setSchema(header.getSchema()); + headerParam.setExamples(header.getExamples()); + headerParam.setExample(header.getExample()); + headerParam.setContent(header.getContent()); + headerParam.setExtensions(header.getExtensions()); + CodegenParameter param = fromParameter(headerParam, imports); + headers.add(param); + } + } + CodegenEncoding ce = new CodegenEncoding( + enc.getContentType(), + headers, + enc.getStyle().toString(), + enc.getExplode().booleanValue(), + enc.getAllowReserved().booleanValue() + ); + String propName = encodingEntry.getKey(); + ceMap.put(propName, ce); + } + } + CodegenProperty schemaProp = fromProperty("schema", mt.getSchema()); + CodegenMediaType codegenMt = new CodegenMediaType(schemaProp, ceMap); + String contentType = contentEntry.getKey(); + cmtContent.put(contentType, codegenMt); + } + return cmtContent; + } + public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { if (body == null) { LOGGER.error("body in fromRequestBody cannot be null!"); @@ -6578,6 +6634,7 @@ public class DefaultCodegen implements CodegenConfig { if (schema == null) { throw new RuntimeException("Request body cannot be null. Possible cause: missing schema in body parameter (OAS v2): " + body); } + codegenParameter.setContent(getContent(body.getContent(), imports)); if (StringUtils.isNotBlank(schema.get$ref())) { name = ModelUtils.getSimpleRef(schema.get$ref()); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index aaede097e3d..28748850f1b 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -3875,4 +3875,76 @@ public class DefaultCodegenTest { assertTrue(pr.isByteArray); assertFalse(pr.getIsString()); } + + @Test + public void testParameterContent() { + DefaultCodegen codegen = new DefaultCodegen(); + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/content-data.yaml"); + codegen.setOpenAPI(openAPI); + String path; + CodegenOperation co; + + path = "/jsonQueryParams"; + co = codegen.fromOperation(path, "GET", openAPI.getPaths().get(path).getGet(), null); + CodegenParameter coordinatesInlineSchema = co.queryParams.get(0); + LinkedHashMap content = coordinatesInlineSchema.getContent(); + assertNotNull(content); + assertEquals(content.keySet(), new HashSet<>(Arrays.asList("application/json"))); + CodegenMediaType mt = content.get("application/json"); + assertNull(mt.getEncoding()); + CodegenProperty cp = mt.getSchema(); + assertTrue(cp.isMap); + assertEquals(cp.complexType, "object"); + + CodegenParameter coordinatesReferencedSchema = co.queryParams.get(1); + content = coordinatesReferencedSchema.getContent(); + mt = content.get("application/json"); + assertNull(mt.getEncoding()); + cp = mt.getSchema(); + assertFalse(cp.isMap); // because it is a referenced schema + assertEquals(cp.complexType, "coordinates"); + } + + @Test + public void testRequestBodyContent() { + DefaultCodegen codegen = new DefaultCodegen(); + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/content-data.yaml"); + codegen.setOpenAPI(openAPI); + String path; + CodegenOperation co; + + path = "/inlineRequestBodySchemasDifferingByContentType"; + co = codegen.fromOperation(path, "POST", openAPI.getPaths().get(path).getPost(), null); + CodegenParameter bodyParameter = co.bodyParam; + LinkedHashMap content = bodyParameter.getContent(); + assertNotNull(content); + assertEquals(content.keySet(), new HashSet<>(Arrays.asList("application/json", "text/plain"))); + CodegenMediaType mt = content.get("application/json"); + assertNull(mt.getEncoding()); + CodegenProperty cp = mt.getSchema(); + assertNotNull(cp); + + mt = content.get("text/plain"); + assertNull(mt.getEncoding()); + cp = mt.getSchema(); + assertNotNull(cp); + // Note: the inline model resolver has a bug for this use case; it extracts an inline request body into a component + // but the schema it references is not string type + + path = "/refRequestBodySchemasDifferingByContentType"; + co = codegen.fromOperation(path, "POST", openAPI.getPaths().get(path).getPost(), null); + bodyParameter = co.bodyParam; + content = bodyParameter.getContent(); + assertNotNull(content); + assertEquals(content.keySet(), new HashSet<>(Arrays.asList("application/json", "text/plain"))); + mt = content.get("application/json"); + assertNull(mt.getEncoding()); + cp = mt.getSchema(); + assertEquals(cp.complexType, "coordinates"); + + mt = content.get("text/plain"); + assertNull(mt.getEncoding()); + cp = mt.getSchema(); + assertTrue(cp.isString); + } } diff --git a/modules/openapi-generator/src/test/resources/3_0/content-data.yaml b/modules/openapi-generator/src/test/resources/3_0/content-data.yaml new file mode 100644 index 00000000000..56228cd3054 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/content-data.yaml @@ -0,0 +1,83 @@ +openapi: 3.0.0 +info: + title: Tests content data in an endpoint parameter and a request body + description: blah +paths: + /jsonQueryParams: + get: + parameters: + - name: coordinatesInlineSchema + in: query + content: + application/json: + schema: + type: object + required: + - lat + - long + properties: + lat: + type: number + long: + type: number + - name: coordinatesReferencedSchema + in: query + content: + application/json: + schema: + $ref: '#/components/schemas/coordinates' + responses: + '201': + description: 'OK' + /inlineRequestBodySchemasDifferingByContentType: + post: + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - lat + - long + properties: + lat: + type: number + long: + type: number + text/plain: + schema: + type: string + minLength: 5 + responses: + 200: + description: OK + /refRequestBodySchemasDifferingByContentType: + post: + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/coordinates' + text/plain: + schema: + $ref: '#/components/schemas/stringWithMinLength' + responses: + 200: + description: OK +components: + schemas: + stringWithMinLength: + type: string + minLength: 5 + coordinates: + type: object + required: + - lat + - long + properties: + lat: + type: number + long: + type: number diff --git a/samples/server/petstore/python-aiohttp-srclayout/src/openapi_server/openapi/openapi.yaml b/samples/server/petstore/python-aiohttp-srclayout/src/openapi_server/openapi/openapi.yaml index 8b70dbaa5fb..416d4ab0b6d 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/src/openapi_server/openapi/openapi.yaml +++ b/samples/server/petstore/python-aiohttp-srclayout/src/openapi_server/openapi/openapi.yaml @@ -680,22 +680,30 @@ components: properties: id: format: int64 + title: id type: integer username: + title: username type: string firstName: + title: firstName type: string lastName: + title: lastName type: string email: + title: email type: string password: + title: password type: string phone: + title: phone type: string userStatus: description: User Status format: int32 + title: userStatus type: integer title: a User type: object @@ -738,15 +746,18 @@ components: properties: id: format: int64 + title: id type: integer category: $ref: '#/components/schemas/Category' name: example: doggie + title: name type: string photoUrls: items: type: string + title: photoUrls type: array xml: name: photoUrl @@ -754,6 +765,7 @@ components: tags: items: $ref: '#/components/schemas/Tag' + title: tags type: array xml: name: tag @@ -764,6 +776,7 @@ components: - available - pending - sold + title: status type: string required: - name diff --git a/samples/server/petstore/python-aiohttp/openapi_server/openapi/openapi.yaml b/samples/server/petstore/python-aiohttp/openapi_server/openapi/openapi.yaml index 8b70dbaa5fb..416d4ab0b6d 100644 --- a/samples/server/petstore/python-aiohttp/openapi_server/openapi/openapi.yaml +++ b/samples/server/petstore/python-aiohttp/openapi_server/openapi/openapi.yaml @@ -680,22 +680,30 @@ components: properties: id: format: int64 + title: id type: integer username: + title: username type: string firstName: + title: firstName type: string lastName: + title: lastName type: string email: + title: email type: string password: + title: password type: string phone: + title: phone type: string userStatus: description: User Status format: int32 + title: userStatus type: integer title: a User type: object @@ -738,15 +746,18 @@ components: properties: id: format: int64 + title: id type: integer category: $ref: '#/components/schemas/Category' name: example: doggie + title: name type: string photoUrls: items: type: string + title: photoUrls type: array xml: name: photoUrl @@ -754,6 +765,7 @@ components: tags: items: $ref: '#/components/schemas/Tag' + title: tags type: array xml: name: tag @@ -764,6 +776,7 @@ components: - available - pending - sold + title: status type: string required: - name diff --git a/samples/server/petstore/python-fastapi/openapi.yaml b/samples/server/petstore/python-fastapi/openapi.yaml index 133f2f16cfc..94256ed0a0f 100644 --- a/samples/server/petstore/python-fastapi/openapi.yaml +++ b/samples/server/petstore/python-fastapi/openapi.yaml @@ -691,22 +691,30 @@ components: properties: id: format: int64 + title: id type: integer username: + title: username type: string firstName: + title: firstName type: string lastName: + title: lastName type: string email: + title: email type: string password: + title: password type: string phone: + title: phone type: string userStatus: description: User Status format: int32 + title: userStatus type: integer title: a User type: object diff --git a/samples/server/petstore/python-flask/openapi_server/openapi/openapi.yaml b/samples/server/petstore/python-flask/openapi_server/openapi/openapi.yaml index 8b402c5f7bb..f94133dcf46 100644 --- a/samples/server/petstore/python-flask/openapi_server/openapi/openapi.yaml +++ b/samples/server/petstore/python-flask/openapi_server/openapi/openapi.yaml @@ -669,22 +669,30 @@ components: properties: id: format: int64 + title: id type: integer username: + title: username type: string firstName: + title: firstName type: string lastName: + title: lastName type: string email: + title: email type: string password: + title: password type: string phone: + title: phone type: string userStatus: description: User Status format: int32 + title: userStatus type: integer title: a User type: object @@ -727,15 +735,18 @@ components: properties: id: format: int64 + title: id type: integer category: $ref: '#/components/schemas/Category' name: example: doggie + title: name type: string photoUrls: items: type: string + title: photoUrls type: array xml: name: photoUrl @@ -743,6 +754,7 @@ components: tags: items: $ref: '#/components/schemas/Tag' + title: tags type: array xml: name: tag @@ -753,6 +765,7 @@ components: - available - pending - sold + title: status type: string required: - name From 6406e5c03162e1ba842cd86ecc691640f2669fd0 Mon Sep 17 00:00:00 2001 From: Tal Kirshboim Date: Tue, 30 Nov 2021 02:33:42 +0100 Subject: [PATCH 37/61] [Kotlin][Multiplatform] Support custom Ktor HTTP client configuration (#10968) * Support using a custom Ktor HTTP client configuration * Remove ApiClient.kt secondary constructor --- .../kotlin-client/libraries/multiplatform/api.mustache | 4 +++- .../multiplatform/infrastructure/ApiClient.kt.mustache | 10 ++++++++-- .../kotlin/org/openapitools/client/apis/PetApi.kt | 4 +++- .../kotlin/org/openapitools/client/apis/StoreApi.kt | 4 +++- .../kotlin/org/openapitools/client/apis/UserApi.kt | 4 +++- .../openapitools/client/infrastructure/ApiClient.kt | 10 ++++++++-- 6 files changed, 28 insertions(+), 8 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache index bbae188effd..c523b913d2a 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/api.mustache @@ -5,6 +5,7 @@ package {{apiPackage}} {{/imports}} import {{packageName}}.infrastructure.* +import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.serializer.KotlinxSerializer @@ -18,8 +19,9 @@ import kotlinx.serialization.encoding.* {{#nonPublicApi}}internal {{/nonPublicApi}}class {{classname}}( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, jsonSerializer: Json = ApiClient.JSON_DEFAULT -) : ApiClient(baseUrl, httpClientEngine, jsonSerializer) { +) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonSerializer) { {{#operation}} /** diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache index 27b6162f121..84836e45e7e 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache @@ -16,6 +16,7 @@ import io.ktor.client.utils.EmptyContent import io.ktor.http.* import io.ktor.http.content.OutgoingContent import io.ktor.http.content.PartData +import kotlin.Unit import kotlinx.serialization.json.Json import {{apiPackage}}.* @@ -25,6 +26,7 @@ import {{packageName}}.auth.* {{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, private val json: Json ) { @@ -32,9 +34,13 @@ import {{packageName}}.auth.* KotlinxSerializer(json).ignoreOutgoingContent() } - private val client: HttpClient by lazy { + private val defaultHttpClientConfig: (HttpClientConfig<*>) -> Unit by lazy { val jsonConfig: JsonFeature.Config.() -> Unit = { this.serializer = this@ApiClient.serializer } - val clientConfig: (HttpClientConfig<*>) -> Unit = { it.install(JsonFeature, jsonConfig) } + { it.install(JsonFeature, jsonConfig) } + } + + private val client: HttpClient by lazy { + val clientConfig: (HttpClientConfig<*>) -> Unit = httpClientConfig ?: defaultHttpClientConfig httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) } {{#hasAuthMethods}} diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt index 2d2f96b6b89..fe81cdf5bc0 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt @@ -24,6 +24,7 @@ import org.openapitools.client.models.ApiResponse import org.openapitools.client.models.Pet import org.openapitools.client.infrastructure.* +import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.serializer.KotlinxSerializer @@ -36,8 +37,9 @@ import kotlinx.serialization.encoding.* class PetApi( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, jsonSerializer: Json = ApiClient.JSON_DEFAULT -) : ApiClient(baseUrl, httpClientEngine, jsonSerializer) { +) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonSerializer) { /** * Add a new pet to the store diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt index eb85ffc9f1c..ab2acfc425f 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -23,6 +23,7 @@ package org.openapitools.client.apis import org.openapitools.client.models.Order import org.openapitools.client.infrastructure.* +import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.serializer.KotlinxSerializer @@ -35,8 +36,9 @@ import kotlinx.serialization.encoding.* class StoreApi( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, jsonSerializer: Json = ApiClient.JSON_DEFAULT -) : ApiClient(baseUrl, httpClientEngine, jsonSerializer) { +) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonSerializer) { /** * Delete purchase order by ID diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt index 4d16f664b83..83832e3cfa9 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt @@ -23,6 +23,7 @@ package org.openapitools.client.apis import org.openapitools.client.models.User import org.openapitools.client.infrastructure.* +import io.ktor.client.HttpClientConfig import io.ktor.client.request.forms.formData import io.ktor.client.engine.HttpClientEngine import io.ktor.client.features.json.serializer.KotlinxSerializer @@ -35,8 +36,9 @@ import kotlinx.serialization.encoding.* class UserApi( baseUrl: String = ApiClient.BASE_URL, httpClientEngine: HttpClientEngine? = null, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, jsonSerializer: Json = ApiClient.JSON_DEFAULT -) : ApiClient(baseUrl, httpClientEngine, jsonSerializer) { +) : ApiClient(baseUrl, httpClientEngine, httpClientConfig, jsonSerializer) { /** * Create user diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 9f25b105953..4fbb14f3f45 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -16,6 +16,7 @@ import io.ktor.client.utils.EmptyContent import io.ktor.http.* import io.ktor.http.content.OutgoingContent import io.ktor.http.content.PartData +import kotlin.Unit import kotlinx.serialization.json.Json import org.openapitools.client.apis.* @@ -25,6 +26,7 @@ import org.openapitools.client.auth.* open class ApiClient( private val baseUrl: String, httpClientEngine: HttpClientEngine?, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, private val json: Json ) { @@ -32,9 +34,13 @@ open class ApiClient( KotlinxSerializer(json).ignoreOutgoingContent() } - private val client: HttpClient by lazy { + private val defaultHttpClientConfig: (HttpClientConfig<*>) -> Unit by lazy { val jsonConfig: JsonFeature.Config.() -> Unit = { this.serializer = this@ApiClient.serializer } - val clientConfig: (HttpClientConfig<*>) -> Unit = { it.install(JsonFeature, jsonConfig) } + { it.install(JsonFeature, jsonConfig) } + } + + private val client: HttpClient by lazy { + val clientConfig: (HttpClientConfig<*>) -> Unit = httpClientConfig ?: defaultHttpClientConfig httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) } private val authentications: kotlin.collections.Map by lazy { From e7ac0eec4b9410b20bef63222089fb174ec5c447 Mon Sep 17 00:00:00 2001 From: jiangyuan <469391363@qq.com> Date: Tue, 30 Nov 2021 09:50:19 +0800 Subject: [PATCH 38/61] [Python] fix model.mustache import (#10988) * fix model.mustache import * add samples file change Co-authored-by: jiangyuan04 --- .../openapi-generator/src/main/resources/python/model.mustache | 2 +- .../python/petstore_api/model/additional_properties_any_type.py | 2 +- .../python/petstore_api/model/additional_properties_array.py | 2 +- .../python/petstore_api/model/additional_properties_boolean.py | 2 +- .../python/petstore_api/model/additional_properties_class.py | 2 +- .../python/petstore_api/model/additional_properties_integer.py | 2 +- .../python/petstore_api/model/additional_properties_number.py | 2 +- .../python/petstore_api/model/additional_properties_object.py | 2 +- .../python/petstore_api/model/additional_properties_string.py | 2 +- samples/client/petstore/python/petstore_api/model/animal.py | 2 +- .../client/petstore/python/petstore_api/model/animal_farm.py | 2 +- .../client/petstore/python/petstore_api/model/api_response.py | 2 +- .../python/petstore_api/model/array_of_array_of_number_only.py | 2 +- .../petstore/python/petstore_api/model/array_of_number_only.py | 2 +- samples/client/petstore/python/petstore_api/model/array_test.py | 2 +- .../client/petstore/python/petstore_api/model/capitalization.py | 2 +- samples/client/petstore/python/petstore_api/model/cat.py | 2 +- samples/client/petstore/python/petstore_api/model/cat_all_of.py | 2 +- samples/client/petstore/python/petstore_api/model/category.py | 2 +- samples/client/petstore/python/petstore_api/model/child.py | 2 +- .../client/petstore/python/petstore_api/model/child_all_of.py | 2 +- samples/client/petstore/python/petstore_api/model/child_cat.py | 2 +- .../petstore/python/petstore_api/model/child_cat_all_of.py | 2 +- samples/client/petstore/python/petstore_api/model/child_dog.py | 2 +- .../petstore/python/petstore_api/model/child_dog_all_of.py | 2 +- .../client/petstore/python/petstore_api/model/child_lizard.py | 2 +- .../petstore/python/petstore_api/model/child_lizard_all_of.py | 2 +- .../client/petstore/python/petstore_api/model/class_model.py | 2 +- samples/client/petstore/python/petstore_api/model/client.py | 2 +- samples/client/petstore/python/petstore_api/model/dog.py | 2 +- samples/client/petstore/python/petstore_api/model/dog_all_of.py | 2 +- .../client/petstore/python/petstore_api/model/enum_arrays.py | 2 +- samples/client/petstore/python/petstore_api/model/enum_class.py | 2 +- samples/client/petstore/python/petstore_api/model/enum_test.py | 2 +- samples/client/petstore/python/petstore_api/model/file.py | 2 +- .../python/petstore_api/model/file_schema_test_class.py | 2 +- .../client/petstore/python/petstore_api/model/format_test.py | 2 +- .../client/petstore/python/petstore_api/model/grandparent.py | 2 +- .../petstore/python/petstore_api/model/grandparent_animal.py | 2 +- .../petstore/python/petstore_api/model/has_only_read_only.py | 2 +- samples/client/petstore/python/petstore_api/model/list.py | 2 +- samples/client/petstore/python/petstore_api/model/map_test.py | 2 +- .../model/mixed_properties_and_additional_properties_class.py | 2 +- .../petstore/python/petstore_api/model/model200_response.py | 2 +- .../client/petstore/python/petstore_api/model/model_return.py | 2 +- samples/client/petstore/python/petstore_api/model/name.py | 2 +- .../client/petstore/python/petstore_api/model/number_only.py | 2 +- .../python/petstore_api/model/number_with_validations.py | 2 +- .../python/petstore_api/model/object_model_with_ref_props.py | 2 +- samples/client/petstore/python/petstore_api/model/order.py | 2 +- samples/client/petstore/python/petstore_api/model/parent.py | 2 +- .../client/petstore/python/petstore_api/model/parent_all_of.py | 2 +- samples/client/petstore/python/petstore_api/model/parent_pet.py | 2 +- samples/client/petstore/python/petstore_api/model/pet.py | 2 +- samples/client/petstore/python/petstore_api/model/player.py | 2 +- .../petstore/python/petstore_api/model/read_only_first.py | 2 +- .../petstore/python/petstore_api/model/special_model_name.py | 2 +- .../petstore/python/petstore_api/model/string_boolean_map.py | 2 +- .../client/petstore/python/petstore_api/model/string_enum.py | 2 +- samples/client/petstore/python/petstore_api/model/tag.py | 2 +- .../petstore/python/petstore_api/model/type_holder_default.py | 2 +- .../petstore/python/petstore_api/model/type_holder_example.py | 2 +- samples/client/petstore/python/petstore_api/model/user.py | 2 +- samples/client/petstore/python/petstore_api/model/xml_item.py | 2 +- .../petstore_api/model/additional_properties_any_type.py | 2 +- .../petstore_api/model/additional_properties_array.py | 2 +- .../petstore_api/model/additional_properties_boolean.py | 2 +- .../petstore_api/model/additional_properties_class.py | 2 +- .../petstore_api/model/additional_properties_integer.py | 2 +- .../petstore_api/model/additional_properties_number.py | 2 +- .../petstore_api/model/additional_properties_object.py | 2 +- .../petstore_api/model/additional_properties_string.py | 2 +- .../petstore_api/model/animal.py | 2 +- .../petstore_api/model/animal_farm.py | 2 +- .../petstore_api/model/api_response.py | 2 +- .../petstore_api/model/array_of_array_of_number_only.py | 2 +- .../petstore_api/model/array_of_number_only.py | 2 +- .../petstore_api/model/array_test.py | 2 +- .../petstore_api/model/capitalization.py | 2 +- .../petstore_api/model/cat.py | 2 +- .../petstore_api/model/cat_all_of.py | 2 +- .../petstore_api/model/category.py | 2 +- .../petstore_api/model/child.py | 2 +- .../petstore_api/model/child_all_of.py | 2 +- .../petstore_api/model/child_cat.py | 2 +- .../petstore_api/model/child_cat_all_of.py | 2 +- .../petstore_api/model/child_dog.py | 2 +- .../petstore_api/model/child_dog_all_of.py | 2 +- .../petstore_api/model/child_lizard.py | 2 +- .../petstore_api/model/child_lizard_all_of.py | 2 +- .../petstore_api/model/class_model.py | 2 +- .../petstore_api/model/client.py | 2 +- .../petstore_api/model/dog.py | 2 +- .../petstore_api/model/dog_all_of.py | 2 +- .../petstore_api/model/enum_arrays.py | 2 +- .../petstore_api/model/enum_class.py | 2 +- .../petstore_api/model/enum_test.py | 2 +- .../petstore_api/model/file.py | 2 +- .../petstore_api/model/file_schema_test_class.py | 2 +- .../petstore_api/model/format_test.py | 2 +- .../petstore_api/model/grandparent.py | 2 +- .../petstore_api/model/grandparent_animal.py | 2 +- .../petstore_api/model/has_only_read_only.py | 2 +- .../petstore_api/model/list.py | 2 +- .../petstore_api/model/map_test.py | 2 +- .../model/mixed_properties_and_additional_properties_class.py | 2 +- .../petstore_api/model/model200_response.py | 2 +- .../petstore_api/model/model_return.py | 2 +- .../petstore_api/model/name.py | 2 +- .../petstore_api/model/number_only.py | 2 +- .../petstore_api/model/number_with_validations.py | 2 +- .../petstore_api/model/object_model_with_ref_props.py | 2 +- .../petstore_api/model/order.py | 2 +- .../petstore_api/model/parent.py | 2 +- .../petstore_api/model/parent_all_of.py | 2 +- .../petstore_api/model/parent_pet.py | 2 +- .../petstore_api/model/pet.py | 2 +- .../petstore_api/model/player.py | 2 +- .../petstore_api/model/read_only_first.py | 2 +- .../petstore_api/model/special_model_name.py | 2 +- .../petstore_api/model/string_boolean_map.py | 2 +- .../petstore_api/model/string_enum.py | 2 +- .../petstore_api/model/tag.py | 2 +- .../petstore_api/model/type_holder_default.py | 2 +- .../petstore_api/model/type_holder_example.py | 2 +- .../petstore_api/model/user.py | 2 +- .../petstore_api/model/xml_item.py | 2 +- .../python/petstore_api/model/additional_properties_class.py | 2 +- .../model/additional_properties_with_array_of_enums.py | 2 +- .../client/petstore/python/petstore_api/model/address.py | 2 +- .../client/petstore/python/petstore_api/model/animal.py | 2 +- .../client/petstore/python/petstore_api/model/animal_farm.py | 2 +- .../client/petstore/python/petstore_api/model/api_response.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/apple.py | 2 +- .../client/petstore/python/petstore_api/model/apple_req.py | 2 +- .../python/petstore_api/model/array_of_array_of_number_only.py | 2 +- .../client/petstore/python/petstore_api/model/array_of_enums.py | 2 +- .../petstore/python/petstore_api/model/array_of_number_only.py | 2 +- .../client/petstore/python/petstore_api/model/array_test.py | 2 +- .../client/petstore/python/petstore_api/model/banana.py | 2 +- .../client/petstore/python/petstore_api/model/banana_req.py | 2 +- .../client/petstore/python/petstore_api/model/basque_pig.py | 2 +- .../client/petstore/python/petstore_api/model/boolean_enum.py | 2 +- .../client/petstore/python/petstore_api/model/capitalization.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/cat.py | 2 +- .../client/petstore/python/petstore_api/model/cat_all_of.py | 2 +- .../client/petstore/python/petstore_api/model/category.py | 2 +- .../client/petstore/python/petstore_api/model/child_cat.py | 2 +- .../petstore/python/petstore_api/model/child_cat_all_of.py | 2 +- .../client/petstore/python/petstore_api/model/class_model.py | 2 +- .../client/petstore/python/petstore_api/model/client.py | 2 +- .../petstore/python/petstore_api/model/complex_quadrilateral.py | 2 +- .../model/composed_one_of_number_with_validations.py | 2 +- .../model/composed_schema_with_props_and_no_add_props.py | 2 +- .../client/petstore/python/petstore_api/model/danish_pig.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/dog.py | 2 +- .../client/petstore/python/petstore_api/model/dog_all_of.py | 2 +- .../client/petstore/python/petstore_api/model/drawing.py | 2 +- .../client/petstore/python/petstore_api/model/enum_arrays.py | 2 +- .../client/petstore/python/petstore_api/model/enum_class.py | 2 +- .../client/petstore/python/petstore_api/model/enum_test.py | 2 +- .../petstore/python/petstore_api/model/equilateral_triangle.py | 2 +- ...fake_post_inline_additional_properties_payload_array_data.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/file.py | 2 +- .../python/petstore_api/model/file_schema_test_class.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/foo.py | 2 +- .../client/petstore/python/petstore_api/model/format_test.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/fruit.py | 2 +- .../client/petstore/python/petstore_api/model/fruit_req.py | 2 +- .../client/petstore/python/petstore_api/model/gm_fruit.py | 2 +- .../python/petstore_api/model/gm_fruit_no_properties.py | 2 +- .../petstore/python/petstore_api/model/grandparent_animal.py | 2 +- .../petstore/python/petstore_api/model/has_only_read_only.py | 2 +- .../petstore/python/petstore_api/model/health_check_result.py | 2 +- .../model/inline_additional_properties_ref_payload.py | 2 +- .../client/petstore/python/petstore_api/model/inline_object6.py | 2 +- .../python/petstore_api/model/inline_response_default.py | 2 +- .../client/petstore/python/petstore_api/model/integer_enum.py | 2 +- .../python/petstore_api/model/integer_enum_one_value.py | 2 +- .../petstore_api/model/integer_enum_with_default_value.py | 2 +- .../petstore/python/petstore_api/model/isosceles_triangle.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/legs.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/list.py | 2 +- .../client/petstore/python/petstore_api/model/mammal.py | 2 +- .../client/petstore/python/petstore_api/model/map_test.py | 2 +- .../model/mixed_properties_and_additional_properties_class.py | 2 +- .../petstore/python/petstore_api/model/model200_response.py | 2 +- .../client/petstore/python/petstore_api/model/model_return.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/mole.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/name.py | 2 +- .../client/petstore/python/petstore_api/model/nullable_class.py | 2 +- .../client/petstore/python/petstore_api/model/nullable_shape.py | 2 +- .../client/petstore/python/petstore_api/model/number_only.py | 2 +- .../python/petstore_api/model/number_with_validations.py | 2 +- .../petstore/python/petstore_api/model/object_interface.py | 2 +- .../python/petstore_api/model/object_model_with_ref_props.py | 2 +- .../python/petstore_api/model/object_with_validations.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/order.py | 2 +- .../client/petstore/python/petstore_api/model/parent_pet.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/pet.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/pig.py | 2 +- .../client/petstore/python/petstore_api/model/quadrilateral.py | 2 +- .../python/petstore_api/model/quadrilateral_interface.py | 2 +- .../petstore/python/petstore_api/model/read_only_first.py | 2 +- .../client/petstore/python/petstore_api/model/readonly.py | 2 +- .../petstore/python/petstore_api/model/scalene_triangle.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/shape.py | 2 +- .../petstore/python/petstore_api/model/shape_interface.py | 2 +- .../client/petstore/python/petstore_api/model/shape_or_null.py | 2 +- .../petstore/python/petstore_api/model/simple_quadrilateral.py | 2 +- .../client/petstore/python/petstore_api/model/some_object.py | 2 +- .../python/petstore_api/model/some_object_with_self_attr.py | 2 +- .../petstore/python/petstore_api/model/special_model_name.py | 2 +- .../petstore/python/petstore_api/model/string_boolean_map.py | 2 +- .../client/petstore/python/petstore_api/model/string_enum.py | 2 +- .../python/petstore_api/model/string_enum_with_default_value.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/tag.py | 2 +- .../client/petstore/python/petstore_api/model/triangle.py | 2 +- .../petstore/python/petstore_api/model/triangle_interface.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/user.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/whale.py | 2 +- .../openapi3/client/petstore/python/petstore_api/model/zebra.py | 2 +- 222 files changed, 222 insertions(+), 222 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/python/model.mustache b/modules/openapi-generator/src/main/resources/python/model.mustache index c8e1bfaa004..e2e70c837de 100644 --- a/modules/openapi-generator/src/main/resources/python/model.mustache +++ b/modules/openapi-generator/src/main/resources/python/model.mustache @@ -16,8 +16,8 @@ from {{packageName}}.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from {{packageName}}.exceptions import ApiAttributeError {{#models}} diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py b/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py index 34ae88833fb..d98c15e0abb 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_any_type.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_array.py b/samples/client/petstore/python/petstore_api/model/additional_properties_array.py index 55f44f411c2..c45c5af7f1f 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_array.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_array.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py b/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py index b9c5c258e3c..de4abb39d43 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_boolean.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_class.py b/samples/client/petstore/python/petstore_api/model/additional_properties_class.py index 7e4d3d93c5f..ae112087fcc 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py b/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py index f6f80f89c7a..cab71552229 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_integer.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_number.py b/samples/client/petstore/python/petstore_api/model/additional_properties_number.py index 6c094699462..5a9b0c623ab 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_number.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_number.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_object.py b/samples/client/petstore/python/petstore_api/model/additional_properties_object.py index 1fa671aff9b..90886578352 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_object.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_object.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/additional_properties_string.py b/samples/client/petstore/python/petstore_api/model/additional_properties_string.py index 0afa8a9e637..07394244c68 100644 --- a/samples/client/petstore/python/petstore_api/model/additional_properties_string.py +++ b/samples/client/petstore/python/petstore_api/model/additional_properties_string.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/animal.py b/samples/client/petstore/python/petstore_api/model/animal.py index fda6c283ebd..ffcbc727b3b 100644 --- a/samples/client/petstore/python/petstore_api/model/animal.py +++ b/samples/client/petstore/python/petstore_api/model/animal.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/animal_farm.py b/samples/client/petstore/python/petstore_api/model/animal_farm.py index 042a8274ee7..0cca3901cb3 100644 --- a/samples/client/petstore/python/petstore_api/model/animal_farm.py +++ b/samples/client/petstore/python/petstore_api/model/animal_farm.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/api_response.py b/samples/client/petstore/python/petstore_api/model/api_response.py index d1f3b363bef..ed202b6bdcc 100644 --- a/samples/client/petstore/python/petstore_api/model/api_response.py +++ b/samples/client/petstore/python/petstore_api/model/api_response.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py b/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py index 16d9bda29f1..39a76641c6d 100644 --- a/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/array_of_number_only.py b/samples/client/petstore/python/petstore_api/model/array_of_number_only.py index 0e44ab61aff..73abf32b511 100644 --- a/samples/client/petstore/python/petstore_api/model/array_of_number_only.py +++ b/samples/client/petstore/python/petstore_api/model/array_of_number_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/array_test.py b/samples/client/petstore/python/petstore_api/model/array_test.py index 64c180d11bc..fc4e6c34537 100644 --- a/samples/client/petstore/python/petstore_api/model/array_test.py +++ b/samples/client/petstore/python/petstore_api/model/array_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/capitalization.py b/samples/client/petstore/python/petstore_api/model/capitalization.py index 2f1323481dc..d5d7202f9af 100644 --- a/samples/client/petstore/python/petstore_api/model/capitalization.py +++ b/samples/client/petstore/python/petstore_api/model/capitalization.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/cat.py b/samples/client/petstore/python/petstore_api/model/cat.py index 9a42057a87e..2764c714e13 100644 --- a/samples/client/petstore/python/petstore_api/model/cat.py +++ b/samples/client/petstore/python/petstore_api/model/cat.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/cat_all_of.py b/samples/client/petstore/python/petstore_api/model/cat_all_of.py index a5bef948f72..0fa2471efdd 100644 --- a/samples/client/petstore/python/petstore_api/model/cat_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/cat_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/category.py b/samples/client/petstore/python/petstore_api/model/category.py index b40329c9424..b4557487e02 100644 --- a/samples/client/petstore/python/petstore_api/model/category.py +++ b/samples/client/petstore/python/petstore_api/model/category.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/child.py b/samples/client/petstore/python/petstore_api/model/child.py index b63ce3fce77..23ef528ea74 100644 --- a/samples/client/petstore/python/petstore_api/model/child.py +++ b/samples/client/petstore/python/petstore_api/model/child.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/child_all_of.py b/samples/client/petstore/python/petstore_api/model/child_all_of.py index e38d28f52d1..148fa59f644 100644 --- a/samples/client/petstore/python/petstore_api/model/child_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/child_cat.py b/samples/client/petstore/python/petstore_api/model/child_cat.py index 355321a2c4c..5fd213c0ce9 100644 --- a/samples/client/petstore/python/petstore_api/model/child_cat.py +++ b/samples/client/petstore/python/petstore_api/model/child_cat.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py b/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py index 48b725d7c3c..21c3ac606b2 100644 --- a/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_cat_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/child_dog.py b/samples/client/petstore/python/petstore_api/model/child_dog.py index ba163cc764c..d49a0fc295c 100644 --- a/samples/client/petstore/python/petstore_api/model/child_dog.py +++ b/samples/client/petstore/python/petstore_api/model/child_dog.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py b/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py index 40d4f048f87..e753ba14538 100644 --- a/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_dog_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/child_lizard.py b/samples/client/petstore/python/petstore_api/model/child_lizard.py index 1a886786955..f714f3d1f90 100644 --- a/samples/client/petstore/python/petstore_api/model/child_lizard.py +++ b/samples/client/petstore/python/petstore_api/model/child_lizard.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py b/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py index b0e9771c580..fe6896926bb 100644 --- a/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/child_lizard_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/class_model.py b/samples/client/petstore/python/petstore_api/model/class_model.py index a3f2b58f87f..d73e8f42ef7 100644 --- a/samples/client/petstore/python/petstore_api/model/class_model.py +++ b/samples/client/petstore/python/petstore_api/model/class_model.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/client.py b/samples/client/petstore/python/petstore_api/model/client.py index 3dca32f7926..091a0605133 100644 --- a/samples/client/petstore/python/petstore_api/model/client.py +++ b/samples/client/petstore/python/petstore_api/model/client.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/dog.py b/samples/client/petstore/python/petstore_api/model/dog.py index b6eed138105..c213921a227 100644 --- a/samples/client/petstore/python/petstore_api/model/dog.py +++ b/samples/client/petstore/python/petstore_api/model/dog.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/dog_all_of.py b/samples/client/petstore/python/petstore_api/model/dog_all_of.py index dbc36cb2c8f..967558a7de8 100644 --- a/samples/client/petstore/python/petstore_api/model/dog_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/dog_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/enum_arrays.py b/samples/client/petstore/python/petstore_api/model/enum_arrays.py index da42763d9c3..56b055e4a51 100644 --- a/samples/client/petstore/python/petstore_api/model/enum_arrays.py +++ b/samples/client/petstore/python/petstore_api/model/enum_arrays.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/enum_class.py b/samples/client/petstore/python/petstore_api/model/enum_class.py index b0ed3d8966d..476d3da6587 100644 --- a/samples/client/petstore/python/petstore_api/model/enum_class.py +++ b/samples/client/petstore/python/petstore_api/model/enum_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/enum_test.py b/samples/client/petstore/python/petstore_api/model/enum_test.py index a3f47184d1a..7ba923a9959 100644 --- a/samples/client/petstore/python/petstore_api/model/enum_test.py +++ b/samples/client/petstore/python/petstore_api/model/enum_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/file.py b/samples/client/petstore/python/petstore_api/model/file.py index 849f5727dc9..90ebbacfefe 100644 --- a/samples/client/petstore/python/petstore_api/model/file.py +++ b/samples/client/petstore/python/petstore_api/model/file.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py b/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py index f7e154e47b7..4dcd9995d8a 100644 --- a/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py +++ b/samples/client/petstore/python/petstore_api/model/file_schema_test_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/format_test.py b/samples/client/petstore/python/petstore_api/model/format_test.py index 1d3ef5f76b4..43c1c21afa8 100644 --- a/samples/client/petstore/python/petstore_api/model/format_test.py +++ b/samples/client/petstore/python/petstore_api/model/format_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/grandparent.py b/samples/client/petstore/python/petstore_api/model/grandparent.py index b92e3acdcf3..c3260576e4b 100644 --- a/samples/client/petstore/python/petstore_api/model/grandparent.py +++ b/samples/client/petstore/python/petstore_api/model/grandparent.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/grandparent_animal.py b/samples/client/petstore/python/petstore_api/model/grandparent_animal.py index fd77a46211f..d57f18a695d 100644 --- a/samples/client/petstore/python/petstore_api/model/grandparent_animal.py +++ b/samples/client/petstore/python/petstore_api/model/grandparent_animal.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/has_only_read_only.py b/samples/client/petstore/python/petstore_api/model/has_only_read_only.py index 33d1c15b58d..967d83544cd 100644 --- a/samples/client/petstore/python/petstore_api/model/has_only_read_only.py +++ b/samples/client/petstore/python/petstore_api/model/has_only_read_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/list.py b/samples/client/petstore/python/petstore_api/model/list.py index 4b71d9deec0..f22e79bdde2 100644 --- a/samples/client/petstore/python/petstore_api/model/list.py +++ b/samples/client/petstore/python/petstore_api/model/list.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/map_test.py b/samples/client/petstore/python/petstore_api/model/map_test.py index 39c3b180e88..5ffaa783df3 100644 --- a/samples/client/petstore/python/petstore_api/model/map_test.py +++ b/samples/client/petstore/python/petstore_api/model/map_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py index f46cd0b8972..780a112d243 100644 --- a/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/model200_response.py b/samples/client/petstore/python/petstore_api/model/model200_response.py index 41a8dee5fdf..4fda496353e 100644 --- a/samples/client/petstore/python/petstore_api/model/model200_response.py +++ b/samples/client/petstore/python/petstore_api/model/model200_response.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/model_return.py b/samples/client/petstore/python/petstore_api/model/model_return.py index f3720b05246..ed436bd3890 100644 --- a/samples/client/petstore/python/petstore_api/model/model_return.py +++ b/samples/client/petstore/python/petstore_api/model/model_return.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/name.py b/samples/client/petstore/python/petstore_api/model/name.py index d46618c88a1..65e733099c6 100644 --- a/samples/client/petstore/python/petstore_api/model/name.py +++ b/samples/client/petstore/python/petstore_api/model/name.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/number_only.py b/samples/client/petstore/python/petstore_api/model/number_only.py index a96d9165056..92d24e178c0 100644 --- a/samples/client/petstore/python/petstore_api/model/number_only.py +++ b/samples/client/petstore/python/petstore_api/model/number_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/number_with_validations.py b/samples/client/petstore/python/petstore_api/model/number_with_validations.py index 5d66fec5ec6..d782cb7492a 100644 --- a/samples/client/petstore/python/petstore_api/model/number_with_validations.py +++ b/samples/client/petstore/python/petstore_api/model/number_with_validations.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py b/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py index 2ef48316f43..68142db9a2b 100644 --- a/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py +++ b/samples/client/petstore/python/petstore_api/model/object_model_with_ref_props.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/order.py b/samples/client/petstore/python/petstore_api/model/order.py index eeefff1513f..eac0013231d 100644 --- a/samples/client/petstore/python/petstore_api/model/order.py +++ b/samples/client/petstore/python/petstore_api/model/order.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/parent.py b/samples/client/petstore/python/petstore_api/model/parent.py index de116a11c76..a4102110d47 100644 --- a/samples/client/petstore/python/petstore_api/model/parent.py +++ b/samples/client/petstore/python/petstore_api/model/parent.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/parent_all_of.py b/samples/client/petstore/python/petstore_api/model/parent_all_of.py index 602e3f610a0..2ec9da892e6 100644 --- a/samples/client/petstore/python/petstore_api/model/parent_all_of.py +++ b/samples/client/petstore/python/petstore_api/model/parent_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/parent_pet.py b/samples/client/petstore/python/petstore_api/model/parent_pet.py index df59bb60ed3..3a3de6bcec9 100644 --- a/samples/client/petstore/python/petstore_api/model/parent_pet.py +++ b/samples/client/petstore/python/petstore_api/model/parent_pet.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/pet.py b/samples/client/petstore/python/petstore_api/model/pet.py index 8946f6d4bea..2a33b0889ab 100644 --- a/samples/client/petstore/python/petstore_api/model/pet.py +++ b/samples/client/petstore/python/petstore_api/model/pet.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/player.py b/samples/client/petstore/python/petstore_api/model/player.py index 50ab531029b..84ca922abd3 100644 --- a/samples/client/petstore/python/petstore_api/model/player.py +++ b/samples/client/petstore/python/petstore_api/model/player.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/read_only_first.py b/samples/client/petstore/python/petstore_api/model/read_only_first.py index 38cb5e2634f..bd2a75175ae 100644 --- a/samples/client/petstore/python/petstore_api/model/read_only_first.py +++ b/samples/client/petstore/python/petstore_api/model/read_only_first.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/special_model_name.py b/samples/client/petstore/python/petstore_api/model/special_model_name.py index cc2e49f6bcb..9a7743a2a42 100644 --- a/samples/client/petstore/python/petstore_api/model/special_model_name.py +++ b/samples/client/petstore/python/petstore_api/model/special_model_name.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/string_boolean_map.py b/samples/client/petstore/python/petstore_api/model/string_boolean_map.py index 05f8527fec1..cb0e03f19e5 100644 --- a/samples/client/petstore/python/petstore_api/model/string_boolean_map.py +++ b/samples/client/petstore/python/petstore_api/model/string_boolean_map.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/string_enum.py b/samples/client/petstore/python/petstore_api/model/string_enum.py index 2397dd59fc9..de5d86886d7 100644 --- a/samples/client/petstore/python/petstore_api/model/string_enum.py +++ b/samples/client/petstore/python/petstore_api/model/string_enum.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/tag.py b/samples/client/petstore/python/petstore_api/model/tag.py index 7db3cee0baa..512587947dd 100644 --- a/samples/client/petstore/python/petstore_api/model/tag.py +++ b/samples/client/petstore/python/petstore_api/model/tag.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/type_holder_default.py b/samples/client/petstore/python/petstore_api/model/type_holder_default.py index be884db9d13..ac3c78a4db2 100644 --- a/samples/client/petstore/python/petstore_api/model/type_holder_default.py +++ b/samples/client/petstore/python/petstore_api/model/type_holder_default.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/type_holder_example.py b/samples/client/petstore/python/petstore_api/model/type_holder_example.py index a0836e32d3f..c12c79c27bb 100644 --- a/samples/client/petstore/python/petstore_api/model/type_holder_example.py +++ b/samples/client/petstore/python/petstore_api/model/type_holder_example.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/user.py b/samples/client/petstore/python/petstore_api/model/user.py index 9c5bc4dfd41..3d0bf626cf9 100644 --- a/samples/client/petstore/python/petstore_api/model/user.py +++ b/samples/client/petstore/python/petstore_api/model/user.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python/petstore_api/model/xml_item.py b/samples/client/petstore/python/petstore_api/model/xml_item.py index 060ed03809c..29e1bfe54e6 100644 --- a/samples/client/petstore/python/petstore_api/model/xml_item.py +++ b/samples/client/petstore/python/petstore_api/model/xml_item.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py index 34ae88833fb..d98c15e0abb 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_any_type.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py index 55f44f411c2..c45c5af7f1f 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_array.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py index b9c5c258e3c..de4abb39d43 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_boolean.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py index 5a38128ad89..5daea08d6ef 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py index f6f80f89c7a..cab71552229 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_integer.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py index 6c094699462..5a9b0c623ab 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_number.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py index 1fa671aff9b..90886578352 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_object.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py index 0afa8a9e637..07394244c68 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/additional_properties_string.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py index d1a9e4afbb0..874bb7f8577 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py index 042a8274ee7..0cca3901cb3 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/animal_farm.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py index 5abc32eafe2..e3342da4b4d 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/api_response.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py index 90586071915..a05dc0dbbad 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_array_of_number_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py index e343a727d6e..ee080ed5d5a 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_of_number_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py index 13649acbe32..3d1146f50cb 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/array_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py index 75a354d2959..797721eebf5 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/capitalization.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py index dd757730af1..9a6866afe82 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py index 5ed2c9cdf28..435f2064427 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/cat_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py index cf8a1384975..9542039484f 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/category.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py index 657121c1a91..981c19faf91 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py index e3f8db2e199..c5ca4d14809 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py index a0f68d481fc..6fbffb9fc08 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py index ceacfbcd7b1..8e5c88070be 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_cat_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py index 55c39ff6518..e6b17573c5b 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py index 41c87c20618..c1e24971772 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_dog_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py index e1f30dcb774..90befa4eb00 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py index f88016d0879..789018bd8fa 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/child_lizard_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py index 0ecc844f84c..44580c1ca6f 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/class_model.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py index 2b4ac4b91a8..0c7ad8a06d4 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/client.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py index d4a4e0192f6..02ec7f30cfe 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py index cdc633dc66f..887c999b895 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/dog_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py index 39fe0ffb838..c96038e71a7 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_arrays.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py index b0ed3d8966d..476d3da6587 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py index a75f4774ae7..c06e9e6f7a9 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/enum_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py index a2beaf44a01..04a45eb77bd 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py index e3f7608e95d..ed37ce5cdd2 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/file_schema_test_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py index 1588b1de053..ee392df1b2d 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/format_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py index c25e0b3f843..02af8c35165 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py index e053af7d538..f092f0a9469 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/grandparent_animal.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py index 294a16ddc46..9dd7a4a74d4 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/has_only_read_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py index 18863e57bc7..8f5755cb1c4 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/list.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py index 61281080799..280f49176af 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/map_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py index 95468963156..efb028619a5 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py index d094c7f84c6..a57ce4b84ca 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model200_response.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py index 51bcf6f1649..8463f340587 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/model_return.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py index 4ee3e1ed2bf..80bdb220039 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/name.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py index c4163787bc1..f5db0482a05 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py index 5d66fec5ec6..d782cb7492a 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/number_with_validations.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py index dfe5d05cf05..a308dbd2013 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/object_model_with_ref_props.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py index b69e94ae36b..620fc237103 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/order.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py index 4b17c55c74a..ff20cef07b5 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py index 97916a1dd4e..ff7c5d02e38 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py index bd36702a7a9..28efff2107f 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/parent_pet.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py index a7b888a2aa3..b51c7d6dcbd 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/pet.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py index 104c4d2900d..8bbd2fa5a2a 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/player.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py index ad0bfbaac11..7dff5dfe68a 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/read_only_first.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py index fa13828d6b9..374c641f75b 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/special_model_name.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py index 05f8527fec1..cb0e03f19e5 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_boolean_map.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py index 2397dd59fc9..de5d86886d7 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/string_enum.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py index 913976557b4..6f7dee860a5 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/tag.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py index b156cbac46e..d6b5b41e7fc 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_default.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py index c7a3f13b63c..d9cce030f11 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/type_holder_example.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py index a3a4019042b..8ed23243239 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/user.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py index 18323416318..bf44ba72c71 100644 --- a/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py +++ b/samples/client/petstore/python_disallowAdditionalPropertiesIfNotPresent/petstore_api/model/xml_item.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py index 6540576f957..0d8a59a4a97 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py index f8e0b8529cc..1846afd1eec 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/additional_properties_with_array_of_enums.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/address.py b/samples/openapi3/client/petstore/python/petstore_api/model/address.py index a7c88b8fec2..01ff154e526 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/address.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/address.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal.py b/samples/openapi3/client/petstore/python/petstore_api/model/animal.py index cc070a6d8fe..8f80b4669b6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py index 042a8274ee7..0cca3901cb3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/animal_farm.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py index d1f3b363bef..ed202b6bdcc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/api_response.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple.py b/samples/openapi3/client/petstore/python/petstore_api/model/apple.py index b5d3d62826d..dee3d8ef80b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/apple.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py index 469aa6e1f6e..b4ce3f132a4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/apple_req.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py index 16d9bda29f1..39a76641c6d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_array_of_number_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py index d83a7f15709..fbe28556441 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_enums.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py index 0e44ab61aff..73abf32b511 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_of_number_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py index 64c180d11bc..fc4e6c34537 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/array_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana.py b/samples/openapi3/client/petstore/python/petstore_api/model/banana.py index 2e2249d2f5e..2d527ca3bbe 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/banana.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py index ff367d1d550..1974ea8a962 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/banana_req.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py index bdf99390952..b7a690cd388 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/basque_pig.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.py index af104c19c78..e19d454603a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/boolean_enum.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py index 2f1323481dc..d5d7202f9af 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/capitalization.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/cat.py b/samples/openapi3/client/petstore/python/petstore_api/model/cat.py index 809db1a2371..03d53416107 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/cat.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py index a5bef948f72..0fa2471efdd 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/cat_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/category.py b/samples/openapi3/client/petstore/python/petstore_api/model/category.py index b40329c9424..b4557487e02 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/category.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/category.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py index 355321a2c4c..5fd213c0ce9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py index 48b725d7c3c..21c3ac606b2 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/child_cat_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py index a3f2b58f87f..d73e8f42ef7 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/class_model.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/client.py b/samples/openapi3/client/petstore/python/petstore_api/model/client.py index 3dca32f7926..091a0605133 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/client.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py index 08f77421bbf..99d9199382a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/complex_quadrilateral.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py index 49d97511457..67429de5a42 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_one_of_number_with_validations.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py b/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py index bd41caf6835..4fd927a1e5c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/composed_schema_with_props_and_no_add_props.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py index c102f99cd28..72ca3e3b2eb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/danish_pig.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/dog.py b/samples/openapi3/client/petstore/python/petstore_api/model/dog.py index b700f88db11..22fbae182f4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/dog.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/dog.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py b/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py index 8e7c1d8f27d..830390f06fa 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/dog_all_of.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py index 41b4a5802c0..68143f247fe 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/drawing.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py index da42763d9c3..56b055e4a51 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_arrays.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py index b0ed3d8966d..476d3da6587 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py index db45011e5ec..924212176dc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/enum_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py index 03ac634dda2..1ef377f5240 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/equilateral_triangle.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py b/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py index bf9761b084c..95faf3468d0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fake_post_inline_additional_properties_payload_array_data.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file.py b/samples/openapi3/client/petstore/python/petstore_api/model/file.py index 849f5727dc9..90ebbacfefe 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/file.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py index f7e154e47b7..4dcd9995d8a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/file_schema_test_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/foo.py b/samples/openapi3/client/petstore/python/petstore_api/model/foo.py index ad17251f73b..e572bea9afe 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/foo.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/foo.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py index 6d4b3b79d70..1cf20a6b1eb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/format_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py index c2971bdb546..deddaf8a739 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py index f428e5cff63..b9ecc53a570 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/fruit_req.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py index 238eb5c8293..d30fc516b05 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit_no_properties.py b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit_no_properties.py index 160b41305b4..d8ddf14ea59 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit_no_properties.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/gm_fruit_no_properties.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py index 1580c5a7b72..7037a228330 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/grandparent_animal.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py index 33d1c15b58d..967d83544cd 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/has_only_read_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py index 0b3818b7c50..a6174163da8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/health_check_result.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py index 85d3fa5922f..861507574d0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_additional_properties_ref_payload.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py index 828d30aa076..b6277de408d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_object6.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py b/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py index b755dbadd36..7e12891bfed 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/inline_response_default.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py index aa397a09ebd..97384f48acf 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py index 0ed72fe14cd..252560ee769 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_one_value.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py index 2c479332983..df7749b22f8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/integer_enum_with_default_value.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py index d2b908e476e..d093a15ac36 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/isosceles_triangle.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/legs.py b/samples/openapi3/client/petstore/python/petstore_api/model/legs.py index 57e01527a85..3258e0a85be 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/legs.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/legs.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/list.py b/samples/openapi3/client/petstore/python/petstore_api/model/list.py index 4b71d9deec0..f22e79bdde2 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/list.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/list.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py index e4e65973278..e06cc8396c0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mammal.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py index 39c3b180e88..5ffaa783df3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/map_test.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py index f46cd0b8972..780a112d243 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mixed_properties_and_additional_properties_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py index 41a8dee5fdf..4fda496353e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model200_response.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py index f3720b05246..ed436bd3890 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/model_return.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/mole.py b/samples/openapi3/client/petstore/python/petstore_api/model/mole.py index 328168b2123..53c2f443ad9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/mole.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/mole.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/name.py b/samples/openapi3/client/petstore/python/petstore_api/model/name.py index d46618c88a1..65e733099c6 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/name.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py index ad5e551dd0f..e038a93fe21 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_class.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py index 90ef787c27f..04bc5a0a345 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/nullable_shape.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py index a96d9165056..92d24e178c0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_only.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py index 9a8a82b4821..068c1c47dfb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/number_with_validations.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py index 23d16918fd6..4b3275bcc8e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_interface.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py index 56a55a14c09..bd98ec208bf 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_model_with_ref_props.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py index dd38862e11b..bbedc4a07fc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/object_with_validations.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/order.py b/samples/openapi3/client/petstore/python/petstore_api/model/order.py index eeefff1513f..eac0013231d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/order.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/order.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py index 8ead627ef6c..f72997edfbc 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/parent_pet.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pet.py b/samples/openapi3/client/petstore/python/petstore_api/model/pet.py index 8946f6d4bea..2a33b0889ab 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pet.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/pig.py b/samples/openapi3/client/petstore/python/petstore_api/model/pig.py index f7f1a953e92..a8e18e7b9fb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/pig.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py index 0afb36e36ac..c5eef71f456 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py index 5ca8fae392a..7f46f6bd626 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/quadrilateral_interface.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py index 38cb5e2634f..bd2a75175ae 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/read_only_first.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py b/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py index 9a98af452eb..7ce992e4714 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/readonly.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py index 518f6d14ca4..d2143ba334e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/scalene_triangle.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape.py index cadcab7e52c..cec42d03322 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py index 0f11d5a1446..313de6aa05e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape_interface.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py index 04c33851616..bde6391563a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/shape_or_null.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py index c4878086ec3..3db924e7dd1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/simple_quadrilateral.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py index 3acbe976bb5..7e650d0dea1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/some_object.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py b/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py index 76e776ae67f..25e24ea8ee5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/some_object_with_self_attr.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py index cc2e49f6bcb..9a7743a2a42 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/special_model_name.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py index 05f8527fec1..cb0e03f19e5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_boolean_map.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py index 3563698aacb..a208eb4780e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py index b6432cdbd1b..2c53501ef3e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/string_enum_with_default_value.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/tag.py b/samples/openapi3/client/petstore/python/petstore_api/model/tag.py index 95a08c18073..9daf411a5bb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/tag.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/tag.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py index 70c34f3a7ac..3329e98a7b7 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py index 783e5fe3bf8..2b88e89e332 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/triangle_interface.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/user.py b/samples/openapi3/client/petstore/python/petstore_api/model/user.py index f77ab381d21..39efcbbc2dd 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/user.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/user.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/whale.py b/samples/openapi3/client/petstore/python/petstore_api/model/whale.py index a8eb263b118..d03a3a7b5c9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/whale.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/whale.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError diff --git a/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py index c348b331671..cd897ef3b6e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py +++ b/samples/openapi3/client/petstore/python/petstore_api/model/zebra.py @@ -24,8 +24,8 @@ from petstore_api.model_utils import ( # noqa: F401 file_type, none_type, validate_get_composed_info, + OpenApiModel ) -from ..model_utils import OpenApiModel from petstore_api.exceptions import ApiAttributeError From b061bd21467c4c9a5de7f4ce551f50d314956e31 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Tue, 30 Nov 2021 15:33:42 +0800 Subject: [PATCH 39/61] [Java][Okhttp] Add oneOf support (#10875) * add custom gson deserializer * add check for additional fields, required fields * add tests for custom deserializer * add custom adapter * add custom adapter * register type adapter factory * comment out custom deserializer and use adapter instead * add okhttp-gson-nextgen * add new files * restore okhttp-gson * switch to adapter * remove custom de/serializer * add comment * update tests * test nextgen in ci * update doc * use full model name in JSON.java * undo changes * add oneof discriminator support * fix anyOf * remove mappings * add more tests * fix oneof deserialization, add more tests * add error body and type to api exception class * JSON to use instance variables/methods * Revert "add error body and type to api exception class" This reverts commit 07f34e2c450ad9f808b728173018b1e4d8fed458. --- bin/configs/java-okhttp-gson-nextgen.yaml | 9 + docs/generators/java.md | 2 +- .../codegen/languages/JavaClientCodegen.java | 11 +- .../AbstractOpenApiSchema.mustache | 138 + .../okhttp-gson-nextgen/ApiCallback.mustache | 51 + .../okhttp-gson-nextgen/ApiClient.mustache | 1737 ++++++++++++ .../okhttp-gson-nextgen/ApiResponse.mustache | 75 + .../GzipRequestInterceptor.mustache | 74 + .../okhttp-gson-nextgen/JSON.mustache | 553 ++++ .../ProgressRequestBody.mustache | 62 + .../ProgressResponseBody.mustache | 59 + .../okhttp-gson-nextgen/README.mustache | 183 ++ .../okhttp-gson-nextgen/anyof_model.mustache | 183 ++ .../okhttp-gson-nextgen/api.mustache | 500 ++++ .../okhttp-gson-nextgen/apiException.mustache | 159 ++ .../okhttp-gson-nextgen/api_doc.mustache | 106 + .../okhttp-gson-nextgen/api_test.mustache | 56 + .../auth/ApiKeyAuth.mustache | 69 + .../auth/Authentication.mustache | 25 + .../auth/HttpBasicAuth.mustache | 46 + .../auth/HttpBearerAuth.mustache | 52 + .../okhttp-gson-nextgen/auth/OAuth.mustache | 31 + .../auth/OAuthOkHttpClient.mustache | 70 + .../auth/RetryingOAuth.mustache | 184 ++ .../okhttp-gson-nextgen/build.gradle.mustache | 169 ++ .../okhttp-gson-nextgen/build.sbt.mustache | 39 + .../okhttp-gson-nextgen/model.mustache | 61 + .../okhttp-gson-nextgen/oneof_model.mustache | 190 ++ .../okhttp-gson-nextgen/pojo.mustache | 445 +++ .../okhttp-gson-nextgen/pom.mustache | 420 +++ ...sting-with-http-signature-okhttp-gson.yaml | 2145 ++++++++++++++ pom.xml | 1 + .../client/model/AbstractOpenApiSchema.java | 149 + .../java/okhttp-gson-nextgen/.gitignore | 21 + .../.openapi-generator-ignore | 14 + .../.openapi-generator/FILES | 195 ++ .../.openapi-generator/VERSION | 1 + .../java/okhttp-gson-nextgen/.travis.yml | 22 + .../java/okhttp-gson-nextgen/README.md | 277 ++ .../java/okhttp-gson-nextgen/api/openapi.yaml | 2464 +++++++++++++++++ .../java/okhttp-gson-nextgen/build.gradle | 153 + .../java/okhttp-gson-nextgen/build.sbt | 27 + .../docs/AdditionalPropertiesAnyType.md | 13 + .../docs/AdditionalPropertiesArray.md | 13 + .../docs/AdditionalPropertiesBoolean.md | 13 + .../docs/AdditionalPropertiesClass.md | 20 + .../docs/AdditionalPropertiesInteger.md | 13 + .../docs/AdditionalPropertiesNumber.md | 13 + .../docs/AdditionalPropertiesObject.md | 13 + .../docs/AdditionalPropertiesString.md | 13 + .../java/okhttp-gson-nextgen/docs/Animal.md | 14 + .../okhttp-gson-nextgen/docs/AnimalFarm.md | 9 + .../docs/AnotherFakeApi.md | 71 + .../java/okhttp-gson-nextgen/docs/Apple.md | 14 + .../java/okhttp-gson-nextgen/docs/AppleReq.md | 14 + .../docs/ArrayOfArrayOfNumberOnly.md | 13 + .../docs/ArrayOfNumberOnly.md | 13 + .../okhttp-gson-nextgen/docs/ArrayTest.md | 15 + .../java/okhttp-gson-nextgen/docs/Banana.md | 13 + .../okhttp-gson-nextgen/docs/BananaReq.md | 14 + .../okhttp-gson-nextgen/docs/BasquePig.md | 13 + .../java/okhttp-gson-nextgen/docs/BigCat.md | 24 + .../okhttp-gson-nextgen/docs/BigCatAllOf.md | 24 + .../docs/Capitalization.md | 18 + .../java/okhttp-gson-nextgen/docs/Cat.md | 13 + .../java/okhttp-gson-nextgen/docs/CatAllOf.md | 13 + .../java/okhttp-gson-nextgen/docs/Category.md | 14 + .../java/okhttp-gson-nextgen/docs/ChildCat.md | 22 + .../okhttp-gson-nextgen/docs/ChildCatAllOf.md | 22 + .../okhttp-gson-nextgen/docs/ClassModel.md | 14 + .../java/okhttp-gson-nextgen/docs/Client.md | 13 + .../docs/ComplexQuadrilateral.md | 14 + .../okhttp-gson-nextgen/docs/DanishPig.md | 13 + .../okhttp-gson-nextgen/docs/DefaultApi.md | 65 + .../docs/DeprecatedObject.md | 13 + .../java/okhttp-gson-nextgen/docs/Dog.md | 13 + .../java/okhttp-gson-nextgen/docs/DogAllOf.md | 13 + .../java/okhttp-gson-nextgen/docs/Drawing.md | 16 + .../okhttp-gson-nextgen/docs/EnumArrays.md | 32 + .../okhttp-gson-nextgen/docs/EnumClass.md | 15 + .../java/okhttp-gson-nextgen/docs/EnumTest.md | 68 + .../docs/EquilateralTriangle.md | 14 + .../java/okhttp-gson-nextgen/docs/FakeApi.md | 1006 +++++++ .../docs/FakeClassnameTags123Api.md | 78 + .../docs/FileSchemaTestClass.md | 14 + .../java/okhttp-gson-nextgen/docs/Foo.md | 13 + .../okhttp-gson-nextgen/docs/FormatTest.md | 28 + .../java/okhttp-gson-nextgen/docs/Fruit.md | 16 + .../java/okhttp-gson-nextgen/docs/FruitReq.md | 16 + .../java/okhttp-gson-nextgen/docs/GmFruit.md | 16 + .../docs/GrandparentAnimal.md | 13 + .../docs/HasOnlyReadOnly.md | 14 + .../docs/HealthCheckResult.md | 14 + .../docs/InlineResponseDefault.md | 13 + .../docs/IsoscelesTriangle.md | 14 + .../java/okhttp-gson-nextgen/docs/Mammal.md | 26 + .../java/okhttp-gson-nextgen/docs/MapTest.md | 25 + ...dPropertiesAndAdditionalPropertiesClass.md | 15 + .../docs/Model200Response.md | 15 + .../docs/ModelApiResponse.md | 15 + .../okhttp-gson-nextgen/docs/ModelReturn.md | 14 + .../java/okhttp-gson-nextgen/docs/Name.md | 17 + .../okhttp-gson-nextgen/docs/NullableClass.md | 24 + .../okhttp-gson-nextgen/docs/NullableShape.md | 15 + .../okhttp-gson-nextgen/docs/NumberOnly.md | 13 + .../docs/ObjectWithDeprecatedFields.md | 16 + .../java/okhttp-gson-nextgen/docs/Order.md | 28 + .../docs/OuterComposite.md | 15 + .../okhttp-gson-nextgen/docs/OuterEnum.md | 15 + .../docs/OuterEnumDefaultValue.md | 15 + .../docs/OuterEnumInteger.md | 15 + .../docs/OuterEnumIntegerDefaultValue.md | 15 + .../okhttp-gson-nextgen/docs/ParentPet.md | 12 + .../java/okhttp-gson-nextgen/docs/Pet.md | 28 + .../java/okhttp-gson-nextgen/docs/PetApi.md | 630 +++++ .../java/okhttp-gson-nextgen/docs/Pig.md | 13 + .../okhttp-gson-nextgen/docs/Quadrilateral.md | 14 + .../docs/QuadrilateralInterface.md | 13 + .../okhttp-gson-nextgen/docs/ReadOnlyFirst.md | 14 + .../docs/ScaleneTriangle.md | 14 + .../java/okhttp-gson-nextgen/docs/Shape.md | 14 + .../docs/ShapeInterface.md | 13 + .../okhttp-gson-nextgen/docs/ShapeOrNull.md | 15 + .../docs/SimpleQuadrilateral.md | 14 + .../docs/SpecialModelName.md | 14 + .../java/okhttp-gson-nextgen/docs/StoreApi.md | 264 ++ .../docs/StringBooleanMap.md | 9 + .../java/okhttp-gson-nextgen/docs/Tag.md | 14 + .../java/okhttp-gson-nextgen/docs/Triangle.md | 14 + .../docs/TriangleInterface.md | 13 + .../docs/TypeHolderDefault.md | 17 + .../docs/TypeHolderExample.md | 18 + .../java/okhttp-gson-nextgen/docs/User.md | 24 + .../java/okhttp-gson-nextgen/docs/UserApi.md | 501 ++++ .../java/okhttp-gson-nextgen/docs/Whale.md | 15 + .../java/okhttp-gson-nextgen/docs/XmlItem.md | 41 + .../java/okhttp-gson-nextgen/docs/Zebra.md | 24 + .../java/okhttp-gson-nextgen/git_push.sh | 57 + .../okhttp-gson-nextgen/gradle.properties | 6 + .../gradle/wrapper/gradle-wrapper.jar | Bin 0 -> 59536 bytes .../gradle/wrapper/gradle-wrapper.properties | 5 + .../petstore/java/okhttp-gson-nextgen/gradlew | 234 ++ .../java/okhttp-gson-nextgen/gradlew.bat | 89 + .../java/okhttp-gson-nextgen/hello.txt | 1 + .../petstore/java/okhttp-gson-nextgen/pom.xml | 349 +++ .../java/okhttp-gson-nextgen/settings.gradle | 1 + .../src/main/AndroidManifest.xml | 3 + .../org/openapitools/client/ApiCallback.java | 62 + .../org/openapitools/client/ApiClient.java | 1552 +++++++++++ .../org/openapitools/client/ApiException.java | 154 ++ .../org/openapitools/client/ApiResponse.java | 76 + .../openapitools/client/Configuration.java | 39 + .../client/GzipRequestInterceptor.java | 85 + .../java/org/openapitools/client/JSON.java | 594 ++++ .../java/org/openapitools/client/Pair.java | 61 + .../client/ProgressRequestBody.java | 73 + .../client/ProgressResponseBody.java | 70 + .../client/ServerConfiguration.java | 58 + .../openapitools/client/ServerVariable.java | 23 + .../org/openapitools/client/StringUtil.java | 83 + .../client/api/AnotherFakeApi.java | 170 ++ .../openapitools/client/api/DefaultApi.java | 161 ++ .../org/openapitools/client/api/FakeApi.java | 2065 ++++++++++++++ .../client/api/FakeClassnameTags123Api.java | 170 ++ .../org/openapitools/client/api/PetApi.java | 1167 ++++++++ .../org/openapitools/client/api/StoreApi.java | 514 ++++ .../org/openapitools/client/api/UserApi.java | 977 +++++++ .../openapitools/client/auth/ApiKeyAuth.java | 80 + .../client/auth/Authentication.java | 36 + .../client/auth/HttpBasicAuth.java | 57 + .../client/auth/HttpBearerAuth.java | 63 + .../org/openapitools/client/auth/OAuth.java | 42 + .../openapitools/client/auth/OAuthFlow.java | 22 + .../client/auth/OAuthOkHttpClient.java | 68 + .../client/auth/RetryingOAuth.java | 182 ++ .../client/model/AbstractOpenApiSchema.java | 149 + .../model/AdditionalPropertiesClass.java | 419 +++ .../org/openapitools/client/model/Animal.java | 203 ++ .../org/openapitools/client/model/Apple.java | 192 ++ .../openapitools/client/model/AppleReq.java | 200 ++ .../model/ArrayOfArrayOfNumberOnly.java | 173 ++ .../client/model/ArrayOfNumberOnly.java | 173 ++ .../openapitools/client/model/ArrayTest.java | 249 ++ .../org/openapitools/client/model/Banana.java | 163 ++ .../openapitools/client/model/BananaReq.java | 201 ++ .../openapitools/client/model/BasquePig.java | 170 ++ .../client/model/Capitalization.java | 312 +++ .../org/openapitools/client/model/Cat.java | 177 ++ .../openapitools/client/model/CatAllOf.java | 162 ++ .../openapitools/client/model/Category.java | 200 ++ .../client/model/ChildCatAllOf.java | 216 ++ .../openapitools/client/model/ClassModel.java | 163 ++ .../org/openapitools/client/model/Client.java | 162 ++ .../client/model/ComplexQuadrilateral.java | 203 ++ .../openapitools/client/model/DanishPig.java | 170 ++ .../client/model/DeprecatedObject.java | 164 ++ .../org/openapitools/client/model/Dog.java | 177 ++ .../openapitools/client/model/DogAllOf.java | 162 ++ .../openapitools/client/model/Drawing.java | 282 ++ .../openapitools/client/model/EnumArrays.java | 296 ++ .../openapitools/client/model/EnumClass.java | 75 + .../openapitools/client/model/EnumTest.java | 665 +++++ .../client/model/EquilateralTriangle.java | 203 ++ .../client/model/FileSchemaTestClass.java | 202 ++ .../org/openapitools/client/model/Foo.java | 162 ++ .../openapitools/client/model/FormatTest.java | 638 +++++ .../org/openapitools/client/model/Fruit.java | 221 ++ .../openapitools/client/model/FruitReq.java | 226 ++ .../openapitools/client/model/GmFruit.java | 216 ++ .../client/model/GrandparentAnimal.java | 172 ++ .../client/model/HasOnlyReadOnly.java | 184 ++ .../client/model/HealthCheckResult.java | 175 ++ .../client/model/InlineResponseDefault.java | 163 ++ .../client/model/IsoscelesTriangle.java | 203 ++ .../org/openapitools/client/model/Mammal.java | 261 ++ .../openapitools/client/model/MapTest.java | 334 +++ ...ropertiesAndAdditionalPropertiesClass.java | 236 ++ .../client/model/Model200Response.java | 193 ++ .../client/model/ModelApiResponse.java | 222 ++ .../client/model/ModelReturn.java | 163 ++ .../org/openapitools/client/model/Name.java | 253 ++ .../client/model/NullableClass.java | 561 ++++ .../client/model/NullableShape.java | 225 ++ .../openapitools/client/model/NumberOnly.java | 163 ++ .../model/ObjectWithDeprecatedFields.java | 270 ++ .../org/openapitools/client/model/Order.java | 362 +++ .../client/model/OuterComposite.java | 223 ++ .../openapitools/client/model/OuterEnum.java | 75 + .../client/model/OuterEnumDefaultValue.java | 75 + .../client/model/OuterEnumInteger.java | 75 + .../model/OuterEnumIntegerDefaultValue.java | 75 + .../openapitools/client/model/ParentPet.java | 144 + .../org/openapitools/client/model/Pet.java | 387 +++ .../org/openapitools/client/model/Pig.java | 220 ++ .../client/model/Quadrilateral.java | 220 ++ .../client/model/QuadrilateralInterface.java | 170 ++ .../client/model/ReadOnlyFirst.java | 191 ++ .../client/model/ScaleneTriangle.java | 203 ++ .../org/openapitools/client/model/Shape.java | 220 ++ .../client/model/ShapeInterface.java | 170 ++ .../client/model/ShapeOrNull.java | 225 ++ .../client/model/SimpleQuadrilateral.java | 203 ++ .../client/model/SpecialModelName.java | 192 ++ .../org/openapitools/client/model/Tag.java | 192 ++ .../openapitools/client/model/Triangle.java | 261 ++ .../client/model/TriangleInterface.java | 170 ++ .../org/openapitools/client/model/User.java | 504 ++++ .../org/openapitools/client/model/Whale.java | 230 ++ .../org/openapitools/client/model/Zebra.java | 253 ++ .../openapitools/client/ApiClientTest.java | 345 +++ .../client/ConfigurationTest.java | 15 + .../org/openapitools/client/JSONTest.java | 348 +++ .../openapitools/client/StringUtilTest.java | 33 + .../client/api/AnotherFakeApiTest.java | 41 + .../client/api/DefaultApiTest.java | 49 + .../openapitools/client/api/FakeApiTest.java | 302 ++ .../api/FakeClassnameTags123ApiTest.java | 41 + .../openapitools/client/api/PetApiTest.java | 575 ++++ .../openapitools/client/api/StoreApiTest.java | 86 + .../openapitools/client/api/UserApiTest.java | 138 + .../client/auth/ApiKeyAuthTest.java | 119 + .../client/auth/HttpBasicAuthTest.java | 65 + .../client/auth/RetryingOAuthTest.java | 123 + .../model/AdditionalPropertiesClassTest.java | 111 + .../openapitools/client/model/AnimalTest.java | 61 + .../client/model/AppleReqTest.java | 59 + .../openapitools/client/model/AppleTest.java | 59 + .../client/model/ArrayOfNumberOnlyTest.java | 54 + .../client/model/ArrayTestTest.java | 70 + .../client/model/BananaReqTest.java | 60 + .../openapitools/client/model/BananaTest.java | 52 + .../client/model/BasquePigTest.java | 51 + .../client/model/CapitalizationTest.java | 91 + .../client/model/CatAllOfTest.java | 51 + .../openapitools/client/model/CatTest.java | 69 + .../client/model/CategoryTest.java | 59 + .../client/model/ClassModelTest.java | 51 + .../openapitools/client/model/ClientTest.java | 51 + .../model/ComplexQuadrilateralTest.java | 61 + .../client/model/DanishPigTest.java | 51 + .../client/model/DeprecatedObjectTest.java | 51 + .../client/model/DogAllOfTest.java | 51 + .../openapitools/client/model/DogTest.java | 69 + .../client/model/DrawingTest.java | 84 + .../client/model/EnumArraysTest.java | 61 + .../client/model/EnumClassTest.java | 34 + .../client/model/EnumTestTest.java | 120 + .../client/model/EquilateralTriangleTest.java | 61 + .../client/model/FileSchemaTestClassTest.java | 61 + .../openapitools/client/model/FooTest.java | 51 + .../client/model/FormatTestTest.java | 176 ++ .../client/model/FruitReqTest.java | 78 + .../openapitools/client/model/FruitTest.java | 70 + .../client/model/GmFruitTest.java | 70 + .../client/model/GrandparentAnimalTest.java | 52 + .../client/model/HasOnlyReadOnlyTest.java | 59 + .../client/model/HealthCheckResultTest.java | 52 + .../model/InlineResponseDefaultTest.java | 52 + .../client/model/IsoscelesTriangleTest.java | 61 + .../openapitools/client/model/MammalTest.java | 78 + .../client/model/MapTestTest.java | 78 + ...rtiesAndAdditionalPropertiesClassTest.java | 73 + .../client/model/Model200ResponseTest.java | 59 + .../client/model/ModelApiResponseTest.java | 67 + .../client/model/ModelReturnTest.java | 51 + .../openapitools/client/model/NameTest.java | 75 + .../client/model/NullableClassTest.java | 147 + .../client/model/NullableShapeTest.java | 69 + .../client/model/NumberOnlyTest.java | 52 + .../model/ObjectWithDeprecatedFieldsTest.java | 79 + .../openapitools/client/model/OrderTest.java | 92 + .../client/model/OuterCompositeTest.java | 68 + .../model/OuterEnumDefaultValueTest.java | 34 + .../OuterEnumIntegerDefaultValueTest.java | 34 + .../client/model/OuterEnumIntegerTest.java | 34 + .../client/model/OuterEnumTest.java | 34 + .../client/model/ParentPetTest.java | 52 + .../openapitools/client/model/PigTest.java | 53 + .../model/QuadrilateralInterfaceTest.java | 51 + .../client/model/QuadrilateralTest.java | 61 + .../client/model/ReadOnlyFirstTest.java | 59 + .../client/model/ScaleneTriangleTest.java | 61 + .../client/model/ShapeInterfaceTest.java | 51 + .../client/model/ShapeOrNullTest.java | 69 + .../openapitools/client/model/ShapeTest.java | 69 + .../client/model/SimpleQuadrilateralTest.java | 61 + .../client/model/SpecialModelNameTest.java | 59 + .../openapitools/client/model/TagTest.java | 59 + .../client/model/TriangleInterfaceTest.java | 51 + .../client/model/TriangleTest.java | 62 + .../openapitools/client/model/UserTest.java | 140 + .../openapitools/client/model/WhaleTest.java | 67 + .../openapitools/client/model/ZebraTest.java | 61 + .../client/model/AbstractOpenApiSchema.java | 149 + 334 files changed, 48332 insertions(+), 4 deletions(-) create mode 100644 bin/configs/java-okhttp-gson-nextgen.yaml create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/AbstractOpenApiSchema.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiCallback.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiClient.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiResponse.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/GzipRequestInterceptor.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ProgressRequestBody.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ProgressResponseBody.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/README.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/anyof_model.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/apiException.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api_doc.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api_test.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/ApiKeyAuth.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/Authentication.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/HttpBasicAuth.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/HttpBearerAuth.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/OAuth.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/OAuthOkHttpClient.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/RetryingOAuth.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/build.gradle.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/build.sbt.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/model.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/oneof_model.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache create mode 100644 modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pom.mustache create mode 100644 modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml create mode 100644 samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/.gitignore create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator-ignore create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator/FILES create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator/VERSION create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/.travis.yml create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/README.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/api/openapi.yaml create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/build.gradle create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/build.sbt create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesAnyType.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesArray.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesBoolean.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesInteger.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesNumber.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesObject.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesString.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Animal.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AnimalFarm.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AnotherFakeApi.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Apple.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/AppleReq.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayTest.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Banana.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/BananaReq.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/BasquePig.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/BigCat.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/BigCatAllOf.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Capitalization.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Cat.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/CatAllOf.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Category.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ChildCat.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ChildCatAllOf.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ClassModel.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Client.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ComplexQuadrilateral.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/DanishPig.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/DefaultApi.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/DeprecatedObject.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Dog.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/DogAllOf.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Drawing.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumArrays.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumClass.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumTest.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/EquilateralTriangle.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/FakeApi.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/FakeClassnameTags123Api.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/FileSchemaTestClass.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Foo.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/FormatTest.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Fruit.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/FruitReq.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/GmFruit.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/GrandparentAnimal.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/HealthCheckResult.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/InlineResponseDefault.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/IsoscelesTriangle.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Mammal.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/MapTest.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/MixedPropertiesAndAdditionalPropertiesClass.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Model200Response.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ModelApiResponse.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ModelReturn.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Name.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/NullableClass.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/NullableShape.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/NumberOnly.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ObjectWithDeprecatedFields.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Order.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterComposite.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnum.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumDefaultValue.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumInteger.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumIntegerDefaultValue.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ParentPet.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Pet.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/PetApi.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Pig.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Quadrilateral.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/QuadrilateralInterface.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ReadOnlyFirst.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ScaleneTriangle.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Shape.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ShapeInterface.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/ShapeOrNull.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/SimpleQuadrilateral.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/SpecialModelName.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/StoreApi.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/StringBooleanMap.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Tag.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Triangle.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/TriangleInterface.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/TypeHolderDefault.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/TypeHolderExample.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/User.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/UserApi.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Whale.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/XmlItem.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/docs/Zebra.md create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/git_push.sh create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/gradle.properties create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/gradle/wrapper/gradle-wrapper.jar create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/gradle/wrapper/gradle-wrapper.properties create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/gradlew create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/gradlew.bat create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/hello.txt create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/pom.xml create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/settings.gradle create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/AndroidManifest.xml create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiCallback.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiClient.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiException.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiResponse.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/Configuration.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/GzipRequestInterceptor.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/Pair.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ProgressRequestBody.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ProgressResponseBody.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ServerConfiguration.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ServerVariable.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/StringUtil.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/AnotherFakeApi.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/DefaultApi.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/FakeApi.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/PetApi.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/StoreApi.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/UserApi.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/Authentication.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuthFlow.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuthOkHttpClient.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/RetryingOAuth.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Apple.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AppleReq.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Banana.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/BananaReq.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/BasquePig.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Capitalization.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Cat.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/CatAllOf.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Category.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ChildCatAllOf.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ClassModel.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Client.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DanishPig.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DeprecatedObject.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Dog.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DogAllOf.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Drawing.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumArrays.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumClass.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EquilateralTriangle.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Foo.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FormatTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Fruit.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FruitReq.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GmFruit.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/HealthCheckResult.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/InlineResponseDefault.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Mammal.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/MapTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Model200Response.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ModelApiResponse.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ModelReturn.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Name.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NullableClass.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NullableShape.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NumberOnly.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Order.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterComposite.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnum.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumInteger.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ParentPet.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Pet.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Pig.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Quadrilateral.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ScaleneTriangle.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Shape.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ShapeInterface.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ShapeOrNull.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/SpecialModelName.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Tag.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Triangle.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/TriangleInterface.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/User.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Whale.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Zebra.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/ApiClientTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/ConfigurationTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/JSONTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/StringUtilTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/DefaultApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/FakeApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/PetApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/StoreApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/UserApiTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AnimalTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AppleReqTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AppleTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ArrayTestTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BananaReqTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BananaTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BasquePigTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CapitalizationTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CatAllOfTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CatTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CategoryTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ClassModelTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ClientTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DanishPigTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DogAllOfTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DogTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DrawingTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumArraysTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumClassTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumTestTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FooTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FormatTestTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FruitReqTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FruitTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/GmFruitTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/InlineResponseDefaultTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MammalTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MapTestTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/Model200ResponseTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ModelReturnTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NameTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NullableClassTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NullableShapeTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NumberOnlyTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OrderTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterCompositeTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ParentPetTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/PigTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/QuadrilateralTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TagTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TriangleTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/UserTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/WhaleTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ZebraTest.java create mode 100644 samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java diff --git a/bin/configs/java-okhttp-gson-nextgen.yaml b/bin/configs/java-okhttp-gson-nextgen.yaml new file mode 100644 index 00000000000..b6b12f86bdd --- /dev/null +++ b/bin/configs/java-okhttp-gson-nextgen.yaml @@ -0,0 +1,9 @@ +generatorName: java +outputDir: samples/client/petstore/java/okhttp-gson-nextgen +library: okhttp-gson-nextgen +#inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml +templateDir: modules/openapi-generator/src/main/resources/Java +additionalProperties: + artifactId: petstore-okhttp-gson-nextgen + hideGenerationTimestamp: "true" diff --git a/docs/generators/java.md b/docs/generators/java.md index 8b360b4b427..1160c36f8b9 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -38,7 +38,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |invokerPackage|root package for generated code| |org.openapitools.client| |java8|Use Java8 classes instead of third party equivalents. Starting in 5.x, JDK8 is the default and the support for JDK7, JDK6 has been dropped|
    **true**
    Use Java 8 classes such as Base64
    **false**
    Various third party libraries as needed
    |true| |legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C#have this enabled by default).|
    **true**
    The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
    **false**
    The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
    |true| -|library|library template (sub-template) to use|
    **jersey1**
    HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libraries instead.
    **jersey2**
    HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x
    **feign**
    HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.
    **okhttp-gson**
    [DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
    **retrofit2**
    HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)
    **resttemplate**
    HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x
    **webclient**
    HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x
    **resteasy**
    HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x
    **vertx**
    HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x
    **google-api-client**
    HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x
    **rest-assured**
    HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8
    **native**
    HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+
    **microprofile**
    HTTP client: Microprofile client 1.x. JSON processing: JSON-B
    **apache-httpclient**
    HTTP client: Apache httpclient 4.x
    |okhttp-gson| +|library|library template (sub-template) to use|
    **jersey1**
    HTTP client: Jersey client 1.19.x. JSON processing: Jackson 2.9.x. Enable gzip request encoding using '-DuseGzipFeature=true'. IMPORTANT NOTE: jersey 1.x is no longer actively maintained so please upgrade to 'jersey2' or other HTTP libraries instead.
    **jersey2**
    HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x
    **feign**
    HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x.
    **okhttp-gson**
    [DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'.
    **okhttp-gson-nextgen**
    HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x.'. Better support for oneOf/anyOf with breaking changes. Will replace `okhttp-gson` in the 6.0.0 release.
    **retrofit2**
    HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)
    **resttemplate**
    HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x
    **webclient**
    HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x
    **resteasy**
    HTTP client: Resteasy client 3.x. JSON processing: Jackson 2.9.x
    **vertx**
    HTTP client: VertX client 3.x. JSON processing: Jackson 2.9.x
    **google-api-client**
    HTTP client: Google API client 1.x. JSON processing: Jackson 2.9.x
    **rest-assured**
    HTTP client: rest-assured : 4.x. JSON processing: Gson 2.x or Jackson 2.10.x. Only for Java 8
    **native**
    HTTP client: Java native HttpClient. JSON processing: Jackson 2.9.x. Only for Java11+
    **microprofile**
    HTTP client: Microprofile client 1.x. JSON processing: JSON-B
    **apache-httpclient**
    HTTP client: Apache httpclient 4.x
    |okhttp-gson| |licenseName|The name of the license| |Unlicense| |licenseUrl|The URL of the license| |http://unlicense.org| |microprofileFramework|Framework for microprofile. Possible values "kumuluzee"| |null| 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 0d9266020ac..965da6dbd77 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 @@ -80,6 +80,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen public static final String JERSEY2 = "jersey2"; public static final String NATIVE = "native"; public static final String OKHTTP_GSON = "okhttp-gson"; + public static final String OKHTTP_GSON_NEXTGEN = "okhttp-gson-nextgen"; public static final String RESTEASY = "resteasy"; public static final String RESTTEMPLATE = "resttemplate"; public static final String WEBCLIENT = "webclient"; @@ -168,6 +169,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportedLibraries.put(JERSEY2, "HTTP client: Jersey client 2.25.1. JSON processing: Jackson 2.9.x"); supportedLibraries.put(FEIGN, "HTTP client: OpenFeign 10.x. JSON processing: Jackson 2.9.x."); supportedLibraries.put(OKHTTP_GSON, "[DEFAULT] HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x. Enable Parcelable models on Android using '-DparcelableModel=true'. Enable gzip request encoding using '-DuseGzipFeature=true'."); + supportedLibraries.put(OKHTTP_GSON_NEXTGEN, "HTTP client: OkHttp 3.x. JSON processing: Gson 2.8.x.'. Better support for oneOf/anyOf with breaking changes. Will replace `okhttp-gson` in the 6.0.0 release."); supportedLibraries.put(RETROFIT_2, "HTTP client: OkHttp 3.x. JSON processing: Gson 2.x (Retrofit 2.3.0). Enable the RxJava adapter using '-DuseRxJava[2/3]=true'. (RxJava 1.x or 2.x or 3.x)"); supportedLibraries.put(RESTTEMPLATE, "HTTP client: Spring RestTemplate 4.x. JSON processing: Jackson 2.9.x"); supportedLibraries.put(WEBCLIENT, "HTTP client: Spring WebClient 5.x. JSON processing: Jackson 2.9.x"); @@ -423,7 +425,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportingFiles.add(new SupportingFile("ParamExpander.mustache", invokerFolder, "ParamExpander.java")); supportingFiles.add(new SupportingFile("EncodingUtils.mustache", invokerFolder, "EncodingUtils.java")); supportingFiles.add(new SupportingFile("auth/DefaultApi20Impl.mustache", authFolder, "DefaultApi20Impl.java")); - } else if (OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) { + } else if (OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary()) || OKHTTP_GSON_NEXTGEN.equals(getLibrary())) { // the "okhttp-gson" library template requires "ApiCallback.mustache" for async call supportingFiles.add(new SupportingFile("ApiCallback.mustache", invokerFolder, "ApiCallback.java")); supportingFiles.add(new SupportingFile("ApiResponse.mustache", invokerFolder, "ApiResponse.java")); @@ -431,6 +433,9 @@ public class JavaClientCodegen extends AbstractJavaCodegen supportingFiles.add(new SupportingFile("ProgressRequestBody.mustache", invokerFolder, "ProgressRequestBody.java")); supportingFiles.add(new SupportingFile("ProgressResponseBody.mustache", invokerFolder, "ProgressResponseBody.java")); supportingFiles.add(new SupportingFile("GzipRequestInterceptor.mustache", invokerFolder, "GzipRequestInterceptor.java")); + if (OKHTTP_GSON_NEXTGEN.equals(getLibrary())) { + supportingFiles.add(new SupportingFile("AbstractOpenApiSchema.mustache", modelsFolder, "AbstractOpenApiSchema.java")); + } // NOTE: below moved to postProcessOperationsWithModels //supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); @@ -615,7 +620,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen // has OAuth defined if (ProcessUtils.hasOAuthMethods(openAPI)) { // for okhttp-gson (default), check to see if OAuth is defined and included OAuth-related files accordingly - if ((OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary()))) { + if ((OKHTTP_GSON.equals(getLibrary()) || StringUtils.isEmpty(getLibrary())) || OKHTTP_GSON_NEXTGEN.equals(getLibrary())) { supportingFiles.add(new SupportingFile("auth/OAuthOkHttpClient.mustache", authFolder, "OAuthOkHttpClient.java")); supportingFiles.add(new SupportingFile("auth/RetryingOAuth.mustache", authFolder, "RetryingOAuth.java")); } @@ -916,7 +921,7 @@ public class JavaClientCodegen extends AbstractJavaCodegen CodegenModel cm = (CodegenModel) mo.get("model"); cm.getVendorExtensions().putIfAbsent("x-implements", new ArrayList()); - if (JERSEY2.equals(getLibrary()) || NATIVE.equals(getLibrary())) { + if (JERSEY2.equals(getLibrary()) || NATIVE.equals(getLibrary()) || OKHTTP_GSON_NEXTGEN.equals(getLibrary())) { cm.getVendorExtensions().put("x-implements", new ArrayList()); if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/AbstractOpenApiSchema.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/AbstractOpenApiSchema.mustache new file mode 100644 index 00000000000..3ba02e44c0e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/AbstractOpenApiSchema.mustache @@ -0,0 +1,138 @@ +{{>licenseInfo}} + +package {{modelPackage}}; + +import {{invokerPackage}}.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 + */ +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}} +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 nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + +{{>libraries/jersey2/additional_properties}} + +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiCallback.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiCallback.mustache new file mode 100644 index 00000000000..53b6a7b8e34 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiCallback.mustache @@ -0,0 +1,51 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API download processing. + * + * @param bytesRead bytes Read + * @param contentLength content length of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiClient.mustache new file mode 100644 index 00000000000..732551cec58 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiClient.mustache @@ -0,0 +1,1737 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +{{#dynamicOperations}} +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.parameters.Parameter.StyleEnum; +import io.swagger.v3.parser.OpenAPIV3Parser; +{{/dynamicOperations}} +import okhttp3.*; +import okhttp3.internal.http.HttpMethod; +import okhttp3.internal.tls.OkHostnameVerifier; +import okhttp3.logging.HttpLoggingInterceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; +{{#joda}} +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +{{/joda}} +{{#threetenbp}} +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.format.DateTimeFormatter; +{{/threetenbp}} +{{#hasOAuthMethods}} +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.common.message.types.GrantType; +{{/hasOAuthMethods}} + +import javax.net.ssl.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; +import java.net.URI; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.text.DateFormat; +{{#java8}} +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +{{/java8}} +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import {{invokerPackage}}.auth.Authentication; +import {{invokerPackage}}.auth.HttpBasicAuth; +import {{invokerPackage}}.auth.HttpBearerAuth; +import {{invokerPackage}}.auth.ApiKeyAuth; +{{#hasOAuthMethods}} +import {{invokerPackage}}.auth.OAuth; +import {{invokerPackage}}.auth.RetryingOAuth; +import {{invokerPackage}}.auth.OAuthFlow; +{{/hasOAuthMethods}} + +/** + *

    ApiClient class.

    + */ +public class ApiClient { + + private String basePath = "{{{basePath}}}"; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private Map defaultCookieMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + private KeyManager[] keyManagers; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + {{#dynamicOperations}} + private Map operationLookupMap = new HashMap<>(); + + {{/dynamicOperations}} + /** + * Basic constructor for ApiClient + */ + public ApiClient() { + init(); + initHttpClient(); + + // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}} + authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Basic constructor with custom OkHttpClient + * + * @param client a {@link okhttp3.OkHttpClient} object + */ + public ApiClient(OkHttpClient client) { + init(); + + httpClient = client; + + // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}} + authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{#isOAuth}} + authentications.put("{{name}}", new OAuth());{{/isOAuth}}{{/authMethods}} + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + {{#hasOAuthMethods}} + {{#oauthMethods}} + {{#-first}} + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID + * + * @param clientId client ID + */ + public ApiClient(String clientId) { + this(clientId, null, null); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID and additional parameters + * + * @param clientId client ID + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, Map parameters) { + this(clientId, null, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID, secret, and additional parameters + * + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, String clientSecret, Map parameters) { + this(null, clientId, clientSecret, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with base path, client ID, secret, and additional parameters + * + * @param basePath base path + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String basePath, String clientId, String clientSecret, Map parameters) { + init(); + if (basePath != null) { + this.basePath = basePath; + } + +{{#hasOAuthMethods}} + String tokenUrl = "{{tokenUrl}}"; + if (!"".equals(tokenUrl) && !URI.create(tokenUrl).isAbsolute()) { + URI uri = URI.create(getBasePath()); + tokenUrl = uri.getScheme() + ":" + + (uri.getAuthority() != null ? "//" + uri.getAuthority() : "") + + tokenUrl; + if (!URI.create(tokenUrl).isAbsolute()) { + throw new IllegalArgumentException("OAuth2 token URL must be an absolute URL"); + } + } + RetryingOAuth retryingOAuth = new RetryingOAuth(tokenUrl, clientId, OAuthFlow.{{flow}}, clientSecret, parameters); + authentications.put( + "{{name}}", + retryingOAuth + ); + initHttpClient(Collections.singletonList(retryingOAuth)); +{{/hasOAuthMethods}} + // Setup authentications (key: authentication name, value: authentication).{{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + authentications.put("{{name}}", new HttpBasicAuth());{{/isBasicBasic}}{{^isBasicBasic}} + authentications.put("{{name}}", new HttpBearerAuth("{{scheme}}"));{{/isBasicBasic}}{{/isBasic}}{{#isApiKey}} + authentications.put("{{name}}", new ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}"));{{/isApiKey}}{{/authMethods}} + + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + {{/-first}} + {{/oauthMethods}} + {{/hasOAuthMethods}} + private void initHttpClient() { + initHttpClient(Collections.emptyList()); + } + + private void initHttpClient(List interceptors) { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.addNetworkInterceptor(getProgressInterceptor()); + for (Interceptor interceptor: interceptors) { + builder.addInterceptor(interceptor); + } + {{#useGzipFeature}} + // Enable gzip request compression + builder.addInterceptor(new GzipRequestInterceptor()); + {{/useGzipFeature}} + + httpClient = builder.build(); + } + + private void init() { + verifyingSsl = true; + + json = new JSON(); + + // Set default User-Agent. + setUserAgent("{{{httpUserAgent}}}{{^httpUserAgent}}OpenAPI-Generator/{{{artifactVersion}}}/java{{/httpUserAgent}}"); + + authentications = new HashMap(); + {{#dynamicOperations}} + + OpenAPI openAPI = new OpenAPIV3Parser().read("openapi/openapi.yaml"); + createOperationLookupMap(openAPI); + {{/dynamicOperations}} + } + + /** + * Get base path + * + * @return Base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g {{{basePath}}} + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client, which must never be null. + * + * @param newHttpClient An instance of OkHttpClient + * @return Api Client + * @throws java.lang.NullPointerException when newHttpClient is null + */ + public ApiClient setHttpClient(OkHttpClient newHttpClient) { + this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + /** + *

    Getter for the field keyManagers.

    + * + * @return an array of {@link javax.net.ssl.KeyManager} objects + */ + public KeyManager[] getKeyManagers() { + return keyManagers; + } + + /** + * Configure client keys to use for authorization in an SSL session. + * Use null to reset to default. + * + * @param managers The KeyManagers to use + * @return ApiClient + */ + public ApiClient setKeyManagers(KeyManager[] managers) { + this.keyManagers = managers; + applySslSettings(); + return this; + } + + /** + *

    Getter for the field dateFormat.

    + * + * @return a {@link java.text.DateFormat} object + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + *

    Setter for the field dateFormat.

    + * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.json.setDateFormat(dateFormat); + return this; + } + + /** + *

    Set SqlDateFormat.

    + * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setSqlDateFormat(DateFormat dateFormat) { + this.json.setSqlDateFormat(dateFormat); + return this; + } + + {{#joda}} + public ApiClient setDateTimeFormat(DateTimeFormatter dateFormat) { + this.json.setDateTimeFormat(dateFormat); + return this; + } + + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + this.json.setLocalDateFormat(dateFormat); + return this; + } + + {{/joda}} + {{#jsr310}} + /** + *

    Set OffsetDateTimeFormat.

    + * + * @param dateFormat a {@link org.threeten.bp.format.DateTimeFormatter} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + this.json.setOffsetDateTimeFormat(dateFormat); + return this; + } + + /** + *

    Set LocalDateFormat.

    + * + * @param dateFormat a {@link org.threeten.bp.format.DateTimeFormatter} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + this.json.setLocalDateFormat(dateFormat); + return this; + } + + {{/jsr310}} + /** + *

    Set LenientOnJson.

    + * + * @param lenientOnJson a boolean + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setLenientOnJson(boolean lenientOnJson) { + this.json.setLenientOnJson(lenientOnJson); + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + 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); + } + + {{#hasHttpBearerMethods}} + /** + * Helper method to set access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + {{/hasHttpBearerMethods}} + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + {{#hasOAuthMethods}} + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + {{/hasOAuthMethods}} + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + 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 ApiClient + */ + 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 enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); + } else { + final OkHttpClient.Builder builder = httpClient.newBuilder(); + builder.interceptors().remove(loggingInterceptor); + httpClient = builder.build(); + loggingInterceptor = null; + } + } + this.debugging = 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 temporary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the temporary folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.connectTimeoutMillis(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get read timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getReadTimeout() { + return httpClient.readTimeoutMillis(); + } + + /** + * Sets the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param readTimeout read timeout in milliseconds + * @return Api client + */ + public ApiClient setReadTimeout(int readTimeout) { + httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get write timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getWriteTimeout() { + return httpClient.writeTimeoutMillis(); + } + + /** + * Sets the write timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param writeTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setWriteTimeout(int writeTimeout) { + httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + {{#hasOAuthMethods}} + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * + * @return Token request builder + */ + public TokenRequestBuilder getTokenEndPoint() { + for (Authentication apiAuth : authentications.values()) { + if (apiAuth instanceof RetryingOAuth) { + RetryingOAuth retryingOAuth = (RetryingOAuth) apiAuth; + return retryingOAuth.getTokenRequestBuilder(); + } + } + return null; + } + {{/hasOAuthMethods}} + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date {{#joda}}|| param instanceof DateTime || param instanceof LocalDate{{/joda}}{{#jsr310}}|| param instanceof OffsetDateTime || param instanceof LocalDate{{/jsr310}}) { + //Serialize to json string and remove the " enclosing characters + String jsonStr = json.serialize(param); + return jsonStr.substring(1, jsonStr.length() - 1); + } 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); + } + } + + /** + * Formats the specified query parameter to a list containing a single {@code Pair} object. + * + * Note that {@code value} must not be a collection. + * + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list containing a single {@code Pair} object. + */ + public List parameterToPair(String name, Object value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value instanceof Collection) { + return params; + } + + params.add(new Pair(name, parameterToString(value))); + return params; + } + + {{^dynamicOperations}} + /** + * Formats the specified collection query parameters to a list of {@code Pair} objects. + * + * Note that the values of each of the returned Pair objects are percent-encoded. + * + * @param collectionFormat The collection format of the parameter. + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list of {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Collection value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { + return params; + } + + // create the params based on the collection format + if ("multi".equals(collectionFormat)) { + for (Object item : value) { + params.add(new Pair(name, escapeString(parameterToString(item)))); + } + return params; + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + // escape all delimiters except commas, which are URI reserved + // characters + if ("ssv".equals(collectionFormat)) { + delimiter = escapeString(" "); + } else if ("tsv".equals(collectionFormat)) { + delimiter = escapeString("\t"); + } else if ("pipes".equals(collectionFormat)) { + delimiter = escapeString("|"); + } + + StringBuilder sb = new StringBuilder(); + for (Object item : value) { + sb.append(delimiter); + sb.append(escapeString(parameterToString(item))); + } + + params.add(new Pair(name, sb.substring(delimiter.length()))); + + return params; + } + {{/dynamicOperations}} + {{#dynamicOperations}} + public List parameterToPairs(Parameter param, Collection value) { + List params = new ArrayList(); + + // preconditions + if (param == null || param.getName() == null || param.getName().isEmpty() || value == null) { + return params; + } + + // create the params based on the collection format + if (StyleEnum.FORM.equals(param.getStyle()) && Boolean.TRUE.equals(param.getExplode())) { + for (Object item : value) { + params.add(new Pair(param.getName(), escapeString(parameterToString(item)))); + } + return params; + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + // escape all delimiters except commas, which are URI reserved + // characters + if (StyleEnum.SPACEDELIMITED.equals(param.getStyle())) { + delimiter = escapeString(" "); + } else if (StyleEnum.PIPEDELIMITED.equals(param.getStyle())) { + delimiter = escapeString("|"); + } + + StringBuilder sb = new StringBuilder(); + for (Object item : value) { + sb.append(delimiter); + sb.append(escapeString(parameterToString(item))); + } + + params.add(new Pair(param.getName(), sb.substring(delimiter.length()))); + + return params; + } + {{/dynamicOperations}} + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param value The value of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(String collectionFormat, Collection value) { + // create the value based on the collection format + if ("multi".equals(collectionFormat)) { + // not valid for path params + return parameterToString(value); + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + if ("ssv".equals(collectionFormat)) { + delimiter = " "; + } else if ("tsv".equals(collectionFormat)) { + delimiter = "\t"; + } else if ("pipes".equals(collectionFormat)) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : value) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + return sb.substring(delimiter.length()); + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * 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 (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + 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, + * returns null. If it matches "any", JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return null; + } + + if (contentTypes[0].equals("*/*")) { + 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 to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws org.openapitools.client.ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws org.openapitools.client.ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(content, MediaType.parse(contentType)); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws org.openapitools.client.ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @return Prepared file for the download + * @throws java.io.IOException If fail to prepare file for download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("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 = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + 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); + } + // Files.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return Files.createTempFile(prefix, suffix).toFile(); + else + return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @return ApiResponse<T> + * @throws org.openapitools.client.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws org.openapitools.client.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + {{#supportStreaming}} + /** + *

    Execute stream.

    + * + * @param call a {@link okhttp3.Call} object + * @param returnType a {@link java.lang.reflect.Type} object + * @return a {@link java.io.InputStream} object + * @throws org.openapitools.client.ApiException if any. + */ + public InputStream executeStream(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + if (!response.isSuccessful()) { + throw new ApiException(response.code(), response.message()); + } + if (response.body() == null) { + return null; + } + return response.body().byteStream(); + } catch (IOException e) { + throw new ApiException(e); + } + } + + {{/supportStreaming}} + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + * @see #execute(Call, Type) + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Call call, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } catch (Exception e) { + callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @return Type + * @throws org.openapitools.client.ApiException If the response has an unsuccessful status code or + * fail to deserialize the response body + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + if (response.body() != null) { + try { + response.body().close(); + } catch (Exception e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP call + * @throws org.openapitools.client.ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + + return httpClient.newCall(request); + } + + /** + * Build an HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP request + * @throws org.openapitools.client.ApiException If fail to serialize the request body object + */ + public Request buildRequest(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams + List allQueryParams = new ArrayList(queryParams); + allQueryParams.addAll(collectionQueryParams); + + final String url = buildUrl(path, queryParams, collectionQueryParams); + + // prepare HTTP request body + RequestBody reqBody; + String contentType = headerParams.get("Content-Type"); + + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create("", MediaType.parse(contentType)); + } + } else { + reqBody = serialize(body, contentType); + } + + // update parameters with authentication settings + updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); + + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + processCookieParams(cookieParams, reqBuilder); + + // Associate callback with request (if not null) so interceptor can + // access it when creating ProgressResponseBody + reqBuilder.tag(callback); + + Request request = null; + + if (callback != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return request; + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams, List collectionQueryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { + String prefix = url.toString().contains("?") ? "&" : "?"; + for (Pair param : collectionQueryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + // collection query parameter value already escaped as part of parameterToPairs + url.append(escapeString(param.getName())).append("=").append(value); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Set cookie parameters to the request builder, including default cookies. + * + * @param cookieParams Cookie parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { + for (Entry param : cookieParams.entrySet()) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + for (Entry param : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(param.getKey())) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + } + } + + /** + * 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 payload HTTP request body + * @param method HTTP method + * @param uri URI + */ + public 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) { + throw new RuntimeException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(parameterToString(param.getValue()), null)); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Get network interceptor to add it to the httpClient to track download progress for + * async requests. + */ + private Interceptor getProgressInterceptor() { + return new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + final Request request = chain.request(); + final Response originalResponse = chain.proceed(request); + if (request.tag() instanceof ApiCallback) { + final ApiCallback callback = (ApiCallback) request.tag(); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), callback)) + .build(); + } + return originalResponse; + } + }; + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + TrustManager[] trustManagers; + HostnameVerifier hostnameVerifier; + if (!verifyingSsl) { + trustManagers = new TrustManager[]{ + new X509TrustManager() { + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[]{}; + } + } + }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + } else { + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + if (sslCaCert == null) { + trustManagerFactory.init((KeyStore) null); + } else { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + trustManagerFactory.init(caKeyStore); + } + trustManagers = trustManagerFactory.getTrustManagers(); + hostnameVerifier = OkHostnameVerifier.INSTANCE; + } + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient = httpClient.newBuilder() + .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) + .hostnameVerifier(hostnameVerifier) + .build(); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } + {{#dynamicOperations}} + + public ApiClient createOperationLookupMap(OpenAPI openAPI) { + operationLookupMap = new HashMap<>(); + for (Map.Entry pathItemEntry : openAPI.getPaths().entrySet()) { + String path = pathItemEntry.getKey(); + PathItem pathItem = pathItemEntry.getValue(); + addOperationLookupEntry(path, "GET", pathItem.getGet()); + addOperationLookupEntry(path, "PUT", pathItem.getPut()); + addOperationLookupEntry(path, "POST", pathItem.getPost()); + addOperationLookupEntry(path, "DELETE", pathItem.getDelete()); + addOperationLookupEntry(path, "OPTIONS", pathItem.getOptions()); + addOperationLookupEntry(path, "HEAD", pathItem.getHead()); + addOperationLookupEntry(path, "PATCH", pathItem.getPatch()); + addOperationLookupEntry(path, "TRACE", pathItem.getTrace()); + } + return this; + } + + private void addOperationLookupEntry(String path, String method, Operation operation) { + if ( operation != null && operation.getOperationId() != null) { + operationLookupMap.put( + operation.getOperationId(), + new ApiOperation(path, method, operation)); + } + } + + public Map getOperationLookupMap() { + return operationLookupMap; + } + + public String fillParametersFromOperation( + Operation operation, + Map paramMap, + String path, + List queryParams, + List collectionQueryParams, + Map headerParams, + Map cookieParams + ) { + for (Map.Entry entry : paramMap.entrySet()) { + Object value = entry.getValue(); + for (Parameter param : operation.getParameters()) { + if (entry.getKey().equals(param.getName())) { + switch (param.getIn()) { + case "path": + path = path.replaceAll("\\{" + param.getName() + "\\}", escapeString(value.toString())); + break; + case "query": + if (value instanceof Collection) { + collectionQueryParams.addAll(parameterToPairs(param, (Collection) value)); + } else { + queryParams.addAll(parameterToPair(param.getName(), value)); + } + break; + case "header": + headerParams.put(param.getName(), parameterToString(value)); + break; + case "cookie": + cookieParams.put(param.getName(), parameterToString(value)); + break; + default: + throw new IllegalStateException("Unexpected param in: " + param.getIn()); + } + + } + } + } + return path; + } + {{/dynamicOperations}} + + /** + * Convert the HTTP request body to a string. + * + * @param request The HTTP request object + * @return The string representation of the HTTP request body + * @throws org.openapitools.client.ApiException If fail to serialize the request body object into a string + */ + private String requestBodyToString(RequestBody requestBody) throws ApiException { + if (requestBody != null) { + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return buffer.readUtf8(); + } catch (final IOException e) { + throw new ApiException(e); + } + } + + // empty http request body + return ""; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiResponse.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiResponse.mustache new file mode 100644 index 00000000000..cecbaac1df2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ApiResponse.mustache @@ -0,0 +1,75 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.util.List; +import java.util.Map; +{{#caseInsensitiveResponseHeaders}} +import java.util.Map.Entry; +import java.util.TreeMap; +{{/caseInsensitiveResponseHeaders}} + +/** + * API response returned by API call. + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + *

    Constructor for ApiResponse.

    + * + * @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); + } + + /** + *

    Constructor for ApiResponse.

    + * + * @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; + {{#caseInsensitiveResponseHeaders}} + Map> responseHeaders = new TreeMap>(String.CASE_INSENSITIVE_ORDER); + for(Entry> entry : headers.entrySet()){ + responseHeaders.put(entry.getKey().toLowerCase(), entry.getValue()); + } + {{/caseInsensitiveResponseHeaders}} + this.headers = {{#caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}; + this.data = data; + } + + /** + *

    Get the status code.

    + * + * @return the status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + *

    Get the headers.

    + * + * @return a {@link java.util.Map} of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + *

    Get the data.

    + * + * @return the data + */ + public T getData() { + return data; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/GzipRequestInterceptor.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/GzipRequestInterceptor.mustache new file mode 100644 index 00000000000..b633aa8f586 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/GzipRequestInterceptor.mustache @@ -0,0 +1,74 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; + +import java.io.IOException; + +/** + * Encodes request bodies using gzip. + * + * Taken from https://github.com/square/okhttp/issues/350 + */ +class GzipRequestInterceptor implements Interceptor { + @Override + public Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { + return chain.proceed(originalRequest); + } + + Request compressedRequest = originalRequest.newBuilder() + .header("Content-Encoding", "gzip") + .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) + .build(); + return chain.proceed(compressedRequest); + } + + private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return new RequestBody() { + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() { + return buffer.size(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + sink.write(buffer.snapshot()); + } + }; + } + + private RequestBody gzip(final RequestBody body) { + return new RequestBody() { + @Override + public MediaType contentType() { + return body.contentType(); + } + + @Override + public long contentLength() { + return -1; // We don't know the compressed length in advance! + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); + body.writeTo(gzipSink); + gzipSink.close(); + } + }; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache new file mode 100644 index 00000000000..91a7905d0bc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache @@ -0,0 +1,553 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; +import io.gsonfire.TypeSelector; +{{#joda}} +import org.joda.time.DateTime; +import org.joda.time.LocalDate; +import org.joda.time.format.DateTimeFormatter; +import org.joda.time.format.DateTimeFormatterBuilder; +import org.joda.time.format.ISODateTimeFormat; +{{/joda}} +{{#threetenbp}} +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.format.DateTimeFormatter; +{{/threetenbp}} + +import okio.ByteString; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.ParsePosition; +{{#java8}} +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +{{/java8}} +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.HashMap; + +/* + * A JSON utility class + * + * NOTE: in the future, this class may be converted to static, which may break + * backward-compatibility + */ +public class JSON { + private Gson gson; + private boolean isLenientOnJson = false; + private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + {{#joda}} + private DateTimeTypeAdapter dateTimeTypeAdapter = new DateTimeTypeAdapter(); + private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + {{/joda}} + {{#jsr310}} + private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); + private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + {{/jsr310}} + private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); + + @SuppressWarnings("unchecked") + public static GsonBuilder createGson() { + GsonFireBuilder fireBuilder = new GsonFireBuilder() + {{#models}} + {{#model}} + {{#discriminator}} + .registerTypeSelector({{modelPackage}}.{{classname}}.class, new TypeSelector<{{modelPackage}}.{{classname}}>() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + {{#mappedModels}} + classByDiscriminatorValue.put("{{mappingName}}"{{^discriminatorCaseSensitive}}.toUpperCase(Locale.ROOT){{/discriminatorCaseSensitive}}, {{modelPackage}}.{{modelName}}.class); + {{/mappedModels}} + classByDiscriminatorValue.put("{{name}}"{{^discriminatorCaseSensitive}}.toUpperCase(Locale.ROOT){{/discriminatorCaseSensitive}}, {{modelPackage}}.{{classname}}.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "{{{propertyBaseName}}}")); + } + }) + {{/discriminator}} + {{/model}} + {{/models}} + ; + GsonBuilder builder = fireBuilder.createGsonBuilder(); + {{#disableHtmlEscaping}} + builder.disableHtmlEscaping(); + {{/disableHtmlEscaping}} + return builder; + } + + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if (null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + /** + * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. + * + * @param classByDiscriminatorValue The map of discriminator values to Java classes. + * @param discriminatorValue The value of the OpenAPI discriminator in the input data. + * @return The Java class that implements the OpenAPI schema + */ + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue{{^discriminatorCaseSensitive}}.toUpperCase(Locale.ROOT){{/discriminatorCaseSensitive}}); + if (null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + + public JSON() { + gson = createGson() + .registerTypeAdapter(Date.class, dateTypeAdapter) + .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) + {{#joda}} + .registerTypeAdapter(DateTime.class, dateTimeTypeAdapter) + .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) + {{/joda}} + {{#jsr310}} + .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) + .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) + {{/jsr310}} + .registerTypeAdapter(byte[].class, byteArrayAdapter) + {{#models}} + {{#model}} + {{^isEnum}} + {{#oneOf}} + {{#-first}} + .registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()) + {{/-first}} + {{/oneOf}} + {{^oneOf}} + {{#anyOf}} + {{#-first}} + .registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()) + {{/-first}} + {{/anyOf}} + {{^anyOf}} + .registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()) + {{/anyOf}} + {{/oneOf}} + {{/isEnum}} + {{/model}} + {{/models}} + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + public void setLenientOnJson(boolean lenientOnJson) { + isLenientOnJson = lenientOnJson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (isLenientOnJson) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw (e); + } + } + } + + /** + * Gson TypeAdapter for Byte Array type + */ + public class ByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(ByteString.of(value).base64()); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); + } + } + } + + {{#joda}} + /** + * Gson TypeAdapter for Joda DateTime type + */ + public class DateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public DateTimeTypeAdapter() { + this(new DateTimeFormatterBuilder() + .append(ISODateTimeFormat.dateTime().getPrinter(), ISODateTimeFormat.dateOptionalTimeParser().getParser()) + .toFormatter()); + } + + public DateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, DateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public DateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseDateTime(date); + } + } + } + + /** + * Gson TypeAdapter for Joda LocalDate type + */ + public class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(ISODateTimeFormat.date()); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.print(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return formatter.parseLocalDate(date); + } + } + } + + public void setDateTimeFormat(DateTimeFormatter dateFormat) { + dateTimeTypeAdapter.setFormat(dateFormat); + } + + public void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + + {{/joda}} + {{#jsr310}} + /** + * Gson TypeAdapter for JSR310 OffsetDateTime type + */ + public class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public OffsetDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + + public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + return OffsetDateTime.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDate type + */ + public class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } + } + + public void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + offsetDateTimeTypeAdapter.setFormat(dateFormat); + } + + public void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + + {{/jsr310}} + /** + * Gson TypeAdapter for java.sql.Date type + * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used + * (more efficient than SimpleDateFormat). + */ + public class SqlDateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public SqlDateTypeAdapter() {} + + public SqlDateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, java.sql.Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = date.toString(); + } + out.value(value); + } + } + + @Override + public java.sql.Date read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return new java.sql.Date(dateFormat.parse(date).getTime()); + } + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } + } + + /** + * Gson TypeAdapter for java.util.Date type + * If the dateFormat is null, ISO8601Utils will be used. + */ + public class DateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public DateTypeAdapter() {} + + public DateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = ISO8601Utils.format(date, true); + } + out.value(value); + } + } + + @Override + public Date read(JsonReader in) throws IOException { + try { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return dateFormat.parse(date); + } + return ISO8601Utils.parse(date, new ParsePosition(0)); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } catch (IllegalArgumentException e) { + throw new JsonParseException(e); + } + } + } + + public void setDateFormat(DateFormat dateFormat) { + dateTypeAdapter.setFormat(dateFormat); + } + + public void setSqlDateFormat(DateFormat dateFormat) { + sqlDateTypeAdapter.setFormat(dateFormat); + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ProgressRequestBody.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ProgressRequestBody.mustache new file mode 100644 index 00000000000..71e1e2b4cbe --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ProgressRequestBody.mustache @@ -0,0 +1,62 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + private final RequestBody requestBody; + + private final ApiCallback callback; + + public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { + this.requestBody = requestBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink bufferedSink = Okio.buffer(sink(sink)); + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ProgressResponseBody.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ProgressResponseBody.mustache new file mode 100644 index 00000000000..45115940b66 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/ProgressResponseBody.mustache @@ -0,0 +1,59 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import okhttp3.MediaType; +import okhttp3.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + private final ResponseBody responseBody; + private final ApiCallback callback; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { + this.responseBody = responseBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/README.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/README.mustache new file mode 100644 index 00000000000..a1a142bd488 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/README.mustache @@ -0,0 +1,183 @@ +# {{artifactId}} + +{{appName}} +- API version: {{appVersion}} +{{^hideGenerationTimestamp}} + - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} + +{{{appDescriptionWithNewLines}}} + +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + + +## Requirements + +Building the API client library requires: +1. Java {{#java8}}1.8{{/java8}}{{^java8}}1.7{{/java8}}+ +2. Maven (3.8.3+)/Gradle (7.2+) + +## 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 + + {{{groupId}}} + {{{artifactId}}} + {{{artifactVersion}}} + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy + repositories { + mavenCentral() // Needed if the '{{{artifactId}}}' jar has been published to maven central. + mavenLocal() // Needed if the '{{{artifactId}}}' jar has been published to the local maven repo. + } + + dependencies { + implementation "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}" + } +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +* `target/{{{artifactId}}}-{{{artifactVersion}}}.jar` +* `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +// Import classes: +import {{{invokerPackage}}}.ApiClient; +import {{{invokerPackage}}}.ApiException; +import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}} +import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}} +import {{{invokerPackage}}}.models.*; +import {{{package}}}.{{{classname}}}; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("{{{basePath}}}"); + {{#hasAuthMethods}} + {{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setUsername("YOUR USERNAME"); + {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{{classname}}} apiInstance = new {{{classname}}}(defaultClient); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}} + .{{{paramName}}}({{{paramName}}}){{/optionalParams}} + .execute();{{/vendorExtensions.x-group-parameters}}{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation for Models + +{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md) +{{/model}}{{/models}} + +## Documentation for Authorization + +{{^authMethods}}All endpoints do not require authorization. +{{/authMethods}}Authentication schemes defined for the API: +{{#authMethods}}### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasic}}- **Type**: HTTP basic authentication +{{/isBasic}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}} +{{/-last}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/anyof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/anyof_model.mustache new file mode 100644 index 00000000000..a4c5c86ca2d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/anyof_model.mustache @@ -0,0 +1,183 @@ +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import {{invokerPackage}}.JSON; + +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { + private static final Logger log = Logger.getLogger({{classname}}.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!{{classname}}.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes '{{classname}}' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + {{#anyOf}} + final TypeAdapter<{{.}}> adapter{{.}} = gson.getDelegateAdapter(this, TypeToken.get({{.}}.class)); + {{/anyOf}} + + return (TypeAdapter) new TypeAdapter<{{classname}}>() { + @Override + public void write(JsonWriter out, {{classname}} value) throws IOException { + {{#anyOf}} + // check if the actual instance is of the type `{{.}}` + if (value.getActualInstance() instanceof {{.}}) { + JsonObject obj = adapter{{.}}.toJsonTree(({{.}})value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + {{/anyOf}} + throw new IOException("Failed to deserialize as the type doesn't match anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}"); + } + + @Override + public {{classname}} read(JsonReader in) throws IOException { + Object deserialized = null; + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + // use discriminator value for faster anyOf lookup + {{classname}} new{{classname}} = new {{classname}}(); + String discriminatorValue = elementAdapter.read(in).getAsJsonObject().get("{{{propertyBaseName}}}").getAsString(); + switch (discriminatorValue) { + {{#mappedModels}} + case "{{{mappingName}}}": + deserialized = gson.fromJson(in, {{{modelName}}}.class); + new{{classname}}.setActualInstance(deserialized); + return new{{classname}}; + {{/mappedModels}} + default: + log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue)); + } + + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + + {{#anyOf}} + // deserialize {{{.}}} + try { + deserialized = gson.fromJson(in, {{.}}.class); + log.log(Level.FINER, "Input data matches schema '{{{.}}}'"); + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(deserialized); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema '{{{.}}}'", e); + } + + {{/anyOf}} + throw new IOException("Failed deserialization for {{classname}}: no match found."); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in anyOf + public static final Map schemas = new HashMap(); + + public {{classname}}() { + super("anyOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); + } + + {{#anyOf}} + public {{classname}}({{{.}}} o) { + super("anyOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); + setActualInstance(o); + } + + {{/anyOf}} + static { + {{#anyOf}} + schemas.put("{{{.}}}", new GenericType<{{{.}}}>() { + }); + {{/anyOf}} + } + + @Override + public Map getSchemas() { + return {{classname}}.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}} + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + {{#isNullable}} + if (instance == null) { + super.setActualInstance(instance); + return; + } + + {{/isNullable}} + {{#anyOf}} + if (instance instanceof {{{.}}}) { + super.setActualInstance(instance); + return; + } + + {{/anyOf}} + throw new RuntimeException("Invalid instance type. Must be {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}"); + } + + /** + * Get the actual instance, which can be the following: + * {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}} + * + * @return The actual instance ({{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + {{#anyOf}} + /** + * Get the actual instance of `{{{.}}}`. If the actual instance is not `{{{.}}}`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `{{{.}}}` + * @throws ClassCastException if the instance is not `{{{.}}}` + */ + public {{{.}}} get{{{.}}}() throws ClassCastException { + return ({{{.}}})super.getActualInstance(); + } + + {{/anyOf}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api.mustache new file mode 100644 index 00000000000..525d56fa5d5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api.mustache @@ -0,0 +1,500 @@ +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiCallback; +import {{invokerPackage}}.ApiClient; +import {{invokerPackage}}.ApiException; +{{#dynamicOperations}} +import {{invokerPackage}}.ApiOperation; +{{/dynamicOperations}} +import {{invokerPackage}}.ApiResponse; +import {{invokerPackage}}.Configuration; +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ProgressRequestBody; +import {{invokerPackage}}.ProgressResponseBody; +{{#performBeanValidation}} +import {{invokerPackage}}.BeanValidationException; +{{/performBeanValidation}} + +import com.google.gson.reflect.TypeToken; +{{#dynamicOperations}} +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.parameters.Parameter; +{{/dynamicOperations}} + +import java.io.IOException; + +{{#useBeanValidation}} +import javax.validation.constraints.*; +{{/useBeanValidation}} +{{#performBeanValidation}} +import javax.validation.ConstraintViolation; +import javax.validation.Validation; +import javax.validation.ValidatorFactory; +import javax.validation.executable.ExecutableValidator; +import java.util.Set; +import java.lang.reflect.Method; +import java.lang.reflect.Type; +{{/performBeanValidation}} + +{{#imports}}import {{import}}; +{{/imports}} + +import java.lang.reflect.Type; +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{#supportStreaming}} +import java.io.InputStream; +{{/supportStreaming}} +{{/fullJavaUtil}} + +{{#operations}} +public class {{classname}} { + private ApiClient localVarApiClient; + + public {{classname}}() { + this(Configuration.getDefaultApiClient()); + } + + public {{classname}}(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + {{#operation}} + {{^vendorExtensions.x-group-parameters}}/** + * Build call for {{operationId}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}} + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
    Status Code Description Response Headers
    {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}}
    + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Call({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException { + Object localVarPostBody = {{#bodyParam}}{{paramName}}{{/bodyParam}}{{^bodyParam}}null{{/bodyParam}}; + + // create path and map variables + {{^dynamicOperations}} + String localVarPath = "{{{path}}}"{{#pathParams}} + .replaceAll("\\{" + "{{baseName}}" + "\\}", localVarApiClient.escapeString({{#collectionFormat}}localVarApiClient.collectionPathParameterToString("{{{collectionFormat}}}", {{{paramName}}}){{/collectionFormat}}{{^collectionFormat}}{{{paramName}}}.toString(){{/collectionFormat}})){{/pathParams}}; + {{/dynamicOperations}} + {{#dynamicOperations}} + ApiOperation apiOperation = localVarApiClient.getOperationLookupMap().get("{{{operationId}}}"); + if (apiOperation == null) { + throw new ApiException("Operation not found in OAS"); + } + Operation operation = apiOperation.getOperation(); + String localVarPath = apiOperation.getPath(); + Map paramMap = new HashMap<>(); + {{#allParams}} + {{^isFormParam}} + {{^isBodyParam}} + paramMap.put("{{baseName}}", {{paramName}}); + {{/isBodyParam}} + {{/isFormParam}} + {{/allParams}} + {{/dynamicOperations}} + + {{javaUtilPrefix}}List localVarQueryParams = new {{javaUtilPrefix}}ArrayList(); + {{javaUtilPrefix}}List localVarCollectionQueryParams = new {{javaUtilPrefix}}ArrayList(); + {{javaUtilPrefix}}Map localVarHeaderParams = new {{javaUtilPrefix}}HashMap(); + {{javaUtilPrefix}}Map localVarCookieParams = new {{javaUtilPrefix}}HashMap(); + {{javaUtilPrefix}}Map localVarFormParams = new {{javaUtilPrefix}}HashMap(); + + {{#formParams}} + if ({{paramName}} != null) { + localVarFormParams.put("{{baseName}}", {{paramName}}); + } + + {{/formParams}} + {{^dynamicOperations}} + {{#queryParams}} + if ({{paramName}} != null) { + {{#collectionFormat}}localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("{{{.}}}", {{/collectionFormat}}{{^collectionFormat}}localVarQueryParams.addAll(localVarApiClient.parameterToPair({{/collectionFormat}}"{{baseName}}", {{paramName}})); + } + + {{/queryParams}} + {{#headerParams}} + if ({{paramName}} != null) { + localVarHeaderParams.put("{{baseName}}", localVarApiClient.parameterToString({{paramName}})); + } + + {{/headerParams}} + {{#cookieParams}} + if ({{paramName}} != null) { + localVarCookieParams.put("{{baseName}}", localVarApiClient.parameterToString({{paramName}})); + } + + {{/cookieParams}} + {{/dynamicOperations}} + {{#dynamicOperations}} + localVarPath = localVarApiClient.fillParametersFromOperation(operation, paramMap, localVarPath, localVarQueryParams, localVarCollectionQueryParams, localVarHeaderParams, localVarCookieParams); + + {{/dynamicOperations}} + final String[] localVarAccepts = { + {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + {{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}} + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { {{#authMethods}}"{{name}}"{{^-last}}, {{/-last}}{{/authMethods}} }; + return localVarApiClient.buildCall(localVarPath, {{^dynamicOperations}}"{{httpMethod}}"{{/dynamicOperations}}{{#dynamicOperations}}apiOperation.getMethod(){{/dynamicOperations}}, localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + @SuppressWarnings("rawtypes") + private okhttp3.Call {{operationId}}ValidateBeforeCall({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback _callback) throws ApiException { + {{^performBeanValidation}} + {{#allParams}}{{#required}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) { + throw new ApiException("Missing the required parameter '{{paramName}}' when calling {{operationId}}(Async)"); + } + {{/required}}{{/allParams}} + + okhttp3.Call localVarCall = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback); + return localVarCall; + + {{/performBeanValidation}} + {{#performBeanValidation}} + try { + ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); + ExecutableValidator executableValidator = factory.getValidator().forExecutables(); + + Object[] parameterValues = { {{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}} }; + Method method = this.getClass().getMethod("{{operationId}}WithHttpInfo"{{#allParams}}, {{#isArray}}java.util.List{{/isArray}}{{#isMap}}java.util.Map{{/isMap}}{{^isArray}}{{^isMap}}{{{dataType}}}{{/isMap}}{{/isArray}}.class{{/allParams}}); + Set> violations = executableValidator.validateParameters(this, method, + parameterValues); + + if (violations.size() == 0) { + okhttp3.Call localVarCall = {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback); + return localVarCall; + + } else { + throw new BeanValidationException((Set) violations); + } + } catch (NoSuchMethodException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } catch (SecurityException e) { + e.printStackTrace(); + throw new ApiException(e.getMessage()); + } + + {{/performBeanValidation}} + } + + {{^vendorExtensions.x-group-parameters}} + /** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}}{{#returnType}} + * @return {{.}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
    Status Code Description Response Headers
    {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}}
    + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + {{#vendorExtensions.x-streaming}} + public {{#returnType}}InputStream {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { + {{#returnType}}InputStream localVarResp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + return localVarResp;{{/returnType}} + } + {{/vendorExtensions.x-streaming}} + {{^vendorExtensions.x-streaming}} + public {{#returnType}}{{{.}}} {{/returnType}}{{^returnType}}void {{/returnType}}{{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { + {{#returnType}}ApiResponse<{{{.}}}> localVarResp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + return localVarResp.getData();{{/returnType}} + } + {{/vendorExtensions.x-streaming}} + {{/vendorExtensions.x-group-parameters}} + + {{^vendorExtensions.x-group-parameters}}/** + * {{summary}} + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}} + * @return ApiResponse<{{returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
    Status Code Description Response Headers
    {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}}
    + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-streaming}} InputStream {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { + okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null); + {{#returnType}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + return localVarApiClient.executeStream(localVarCall, localVarReturnType);{{/returnType}} + } + {{/vendorExtensions.x-streaming}}{{^vendorExtensions.x-streaming}} ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Void{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{#useBeanValidation}}{{>beanValidationQueryParams}}{{/useBeanValidation}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException { + okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}null); + {{#returnType}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType);{{/returnType}}{{^returnType}}return localVarApiClient.execute(localVarCall);{{/returnType}} + } + {{/vendorExtensions.x-streaming}} + + {{^vendorExtensions.x-group-parameters}}/** + * {{summary}} (asynchronously) + * {{notes}}{{#allParams}} + * @param {{paramName}} {{description}}{{#required}} (required){{/required}}{{^required}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}){{/required}}{{/allParams}} + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
    Status Code Description Response Headers
    {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}}
    + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}private{{/vendorExtensions.x-group-parameters}} okhttp3.Call {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}, {{/allParams}}final ApiCallback<{{{returnType}}}{{^returnType}}Void{{/returnType}}> _callback) throws ApiException { + + okhttp3.Call localVarCall = {{operationId}}ValidateBeforeCall({{#allParams}}{{paramName}}, {{/allParams}}_callback); + {{#returnType}}Type localVarReturnType = new TypeToken<{{{returnType}}}>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback);{{/returnType}}{{^returnType}}localVarApiClient.executeAsync(localVarCall, _callback);{{/returnType}} + return localVarCall; + } + {{#vendorExtensions.x-group-parameters}} + + public class API{{operationId}}Request { + {{#requiredParams}} + private final {{{dataType}}} {{paramName}}; + {{/requiredParams}} + {{#optionalParams}} + private {{{dataType}}} {{paramName}}; + {{/optionalParams}} + + private API{{operationId}}Request({{#requiredParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}) { + {{#requiredParams}} + this.{{paramName}} = {{paramName}}; + {{/requiredParams}} + } + + {{#optionalParams}} + /** + * Set {{paramName}} + * @param {{paramName}} {{description}} (optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}) + * @return API{{operationId}}Request + */ + public API{{operationId}}Request {{paramName}}({{{dataType}}} {{paramName}}) { + this.{{paramName}} = {{paramName}}; + return this; + } + + {{/optionalParams}} + /** + * Build call for {{operationId}} + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
    Status Code Description Response Headers
    {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}}
    + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return {{operationId}}Call({{#allParams}}{{paramName}}, {{/allParams}}_callback); + } + + /** + * Execute {{operationId}} request{{#returnType}} + * @return {{.}}{{/returnType}} + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
    Status Code Description Response Headers
    {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}}
    + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public {{{returnType}}}{{^returnType}}void{{/returnType}} execute() throws ApiException { + {{#returnType}}ApiResponse<{{{.}}}> localVarResp = {{/returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + return localVarResp.getData();{{/returnType}} + } + + /** + * Execute {{operationId}} request with HTTP info returned + * @return ApiResponse<{{returnType}}{{^returnType}}Void{{/returnType}}> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
    Status Code Description Response Headers
    {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}}
    + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public ApiResponse<{{{returnType}}}{{^returnType}}Void{{/returnType}}> executeWithHttpInfo() throws ApiException { + return {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + } + + /** + * Execute {{operationId}} request (asynchronously) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
    Status Code Description Response Headers
    {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}}
    + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public okhttp3.Call executeAsync(final ApiCallback<{{{returnType}}}{{^returnType}}Void{{/returnType}}> _callback) throws ApiException { + return {{operationId}}Async({{#allParams}}{{paramName}}, {{/allParams}}_callback); + } + } + + /** + * {{summary}} + * {{notes}}{{#requiredParams}} + * @param {{paramName}} {{description}} (required){{/requiredParams}} + * @return API{{operationId}}Request + {{#responses.0}} + * @http.response.details + + + {{#responses}} + + {{/responses}} +
    Status Code Description Response Headers
    {{code}} {{message}} {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}}
    + {{/responses.0}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} + {{#externalDocs}} + * {{description}} + * @see {{summary}} Documentation + {{/externalDocs}} + */ + {{#isDeprecated}} + @Deprecated + {{/isDeprecated}} + public API{{operationId}}Request {{operationId}}({{#requiredParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}) { + return new API{{operationId}}Request({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}); + } + {{/vendorExtensions.x-group-parameters}} + {{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/apiException.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/apiException.mustache new file mode 100644 index 00000000000..4bec51da938 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/apiException.mustache @@ -0,0 +1,159 @@ +{{>licenseInfo}} + +package {{invokerPackage}}; + +import java.util.Map; +import java.util.List; +{{#caseInsensitiveResponseHeaders}} +import java.util.Map.Entry; +import java.util.TreeMap; +{{/caseInsensitiveResponseHeaders}} + +/** + *

    ApiException class.

    + */ +@SuppressWarnings("serial") +{{>generatedAnnotation}} +public class ApiException extends{{#useRuntimeException}} RuntimeException {{/useRuntimeException}}{{^useRuntimeException}} Exception {{/useRuntimeException}}{ + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + /** + *

    Constructor for ApiException.

    + */ + public ApiException() {} + + /** + *

    Constructor for ApiException.

    + * + * @param throwable a {@link java.lang.Throwable} object + */ + public ApiException(Throwable throwable) { + super(throwable); + } + + /** + *

    Constructor for ApiException.

    + * + * @param message the error message + */ + public ApiException(String message) { + super(message); + } + + /** + *

    Constructor for ApiException.

    + * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + {{#caseInsensitiveResponseHeaders}} + Map> headers = new TreeMap>(String.CASE_INSENSITIVE_ORDER); + for(Entry> entry : responseHeaders.entrySet()){ + headers.put(entry.getKey().toLowerCase(), entry.getValue()); + } + {{/caseInsensitiveResponseHeaders}} + this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}; + this.responseBody = responseBody; + } + + /** + *

    Constructor for ApiException.

    + * + * @param message the error message + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

    Constructor for ApiException.

    + * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + /** + *

    Constructor for ApiException.

    + * + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

    Constructor for ApiException.

    + * + * @param code HTTP status code + * @param message a {@link java.lang.String} object + */ + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + /** + *

    Constructor for ApiException.

    + * + * @param code HTTP status code + * @param message the error message + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + {{#caseInsensitiveResponseHeaders}} + Map> headers = new TreeMap>(String.CASE_INSENSITIVE_ORDER); + for(Entry> entry : responseHeaders.entrySet()){ + headers.put(entry.getKey().toLowerCase(), entry.getValue()); + } + {{/caseInsensitiveResponseHeaders}} + this.responseHeaders = {{#caseInsensitiveResponseHeaders}}headers{{/caseInsensitiveResponseHeaders}}{{^caseInsensitiveResponseHeaders}}responseHeaders{{/caseInsensitiveResponseHeaders}}; + 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/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api_doc.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api_doc.mustache new file mode 100644 index 00000000000..5a4e3969c93 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api_doc.mustache @@ -0,0 +1,106 @@ +# {{classname}}{{#description}} +{{.}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{operationId}}**{{^vendorExtensions.x-group-parameters}} +> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}){{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}} +> {{#returnType}}{{.}} {{/returnType}}{{operationId}}({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}}.{{paramName}}({{paramName}}){{/optionalParams}}.execute();{{/vendorExtensions.x-group-parameters}} + +{{summary}}{{#notes}} + +{{.}}{{/notes}} + +### Example +```java +// Import classes: +import {{{invokerPackage}}}.ApiClient; +import {{{invokerPackage}}}.ApiException; +import {{{invokerPackage}}}.Configuration;{{#hasAuthMethods}} +import {{{invokerPackage}}}.auth.*;{{/hasAuthMethods}} +import {{{invokerPackage}}}.models.*; +import {{{package}}}.{{{classname}}}; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("{{{basePath}}}"); + {{#hasAuthMethods}} + {{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + HttpBasicAuth {{{name}}} = (HttpBasicAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setUsername("YOUR USERNAME"); + {{{name}}}.setPassword("YOUR PASSWORD");{{/isBasicBasic}}{{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + HttpBearerAuth {{{name}}} = (HttpBearerAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setBearerToken("BEARER TOKEN");{{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + ApiKeyAuth {{{name}}} = (ApiKeyAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //{{{name}}}.setApiKeyPrefix("Token");{{/isApiKey}}{{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + OAuth {{{name}}} = (OAuth) defaultClient.getAuthentication("{{{name}}}"); + {{{name}}}.setAccessToken("YOUR ACCESS TOKEN");{{/isOAuth}} + {{/authMethods}} + {{/hasAuthMethods}} + + {{{classname}}} apiInstance = new {{{classname}}}(defaultClient); + {{#allParams}} + {{{dataType}}} {{{paramName}}} = {{{example}}}; // {{{dataType}}} | {{{description}}} + {{/allParams}} + try { + {{#returnType}}{{{.}}} result = {{/returnType}}apiInstance.{{{operationId}}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}} + .{{{paramName}}}({{{paramName}}}){{/optionalParams}} + .execute();{{/vendorExtensions.x-group-parameters}}{{#returnType}} + System.out.println(result);{{/returnType}} + } catch (ApiException e) { + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{^isContainer}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}}{{/isContainer}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}null (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +**{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api_test.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api_test.mustache new file mode 100644 index 00000000000..98a30a60cd5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/api_test.mustache @@ -0,0 +1,56 @@ +{{>licenseInfo}} + +package {{package}}; + +import {{invokerPackage}}.ApiException; +{{#imports}}import {{import}}; +{{/imports}} +import org.junit.Test; +import org.junit.Ignore; + +{{^fullJavaUtil}} +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +{{#supportStreaming}} +import java.io.InputStream; +{{/supportStreaming}} +{{/fullJavaUtil}} + +/** + * API tests for {{classname}} + */ +@Ignore +public class {{classname}}Test { + + private final {{classname}} api = new {{classname}}(); + + {{#operations}}{{#operation}} + /** + * {{summary}} + * + * {{notes}} + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void {{operationId}}Test() throws ApiException { + {{#allParams}} + {{{dataType}}} {{paramName}} = null; + {{/allParams}} + {{#vendorExtensions.x-streaming}} + InputStream response = api.{{operationId}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}} + .{{paramName}}({{paramName}}){{/optionalParams}} + .execute();{{/vendorExtensions.x-group-parameters}} + {{/vendorExtensions.x-streaming}} + {{^vendorExtensions.x-streaming}} + {{#returnType}}{{{returnType}}} response = {{/returnType}}api.{{operationId}}{{^vendorExtensions.x-group-parameters}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/vendorExtensions.x-group-parameters}}{{#vendorExtensions.x-group-parameters}}({{#requiredParams}}{{paramName}}{{^-last}}, {{/-last}}{{/requiredParams}}){{#optionalParams}} + .{{paramName}}({{paramName}}){{/optionalParams}} + .execute();{{/vendorExtensions.x-group-parameters}} + {{/vendorExtensions.x-streaming}} + // TODO: test validations + } + {{/operation}}{{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/ApiKeyAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/ApiKeyAuth.mustache new file mode 100644 index 00000000000..a0dda669a89 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/ApiKeyAuth.mustache @@ -0,0 +1,69 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} +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/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/Authentication.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/Authentication.mustache new file mode 100644 index 00000000000..c4ad338c793 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/Authentication.mustache @@ -0,0 +1,25 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.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 + * @param payload HTTP request body + * @param method HTTP method + * @param uri URI + * @throws ApiException if failed to update the parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/HttpBasicAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/HttpBasicAuth.mustache new file mode 100644 index 00000000000..417a89e34cc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/HttpBasicAuth.mustache @@ -0,0 +1,46 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import okhttp3.Credentials; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +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; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/HttpBearerAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/HttpBearerAuth.mustache new file mode 100644 index 00000000000..c8a9fce2965 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/HttpBearerAuth.mustache @@ -0,0 +1,52 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} +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/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/OAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/OAuth.mustache new file mode 100644 index 00000000000..34d35985718 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/OAuth.mustache @@ -0,0 +1,31 @@ +{{>licenseInfo}} + +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.Pair; +import {{invokerPackage}}.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +{{>generatedAnnotation}} +public class OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/OAuthOkHttpClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/OAuthOkHttpClient.mustache new file mode 100644 index 00000000000..cb0e8250550 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/OAuthOkHttpClient.mustache @@ -0,0 +1,70 @@ +{{#hasOAuthMethods}} +package {{invokerPackage}}.auth; + +import okhttp3.OkHttpClient; +import okhttp3.MediaType; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +public class OAuthOkHttpClient implements HttpClient { + private OkHttpClient client; + + public OAuthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OAuthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + @Override + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(request.getBody(), mediaType) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + @Override + public void shutdown() { + // Nothing to do here + } +} +{{/hasOAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/RetryingOAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/RetryingOAuth.mustache new file mode 100644 index 00000000000..137e266b5a2 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/auth/RetryingOAuth.mustache @@ -0,0 +1,184 @@ +{{#hasOAuthMethods}} +package {{invokerPackage}}.auth; + +import {{invokerPackage}}.ApiException; +import {{invokerPackage}}.Pair; + +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.util.Map; +import java.util.List; + +public class RetryingOAuth extends OAuth implements Interceptor { + private OAuthClient oAuthClient; + + private TokenRequestBuilder tokenRequestBuilder; + + public RetryingOAuth(OkHttpClient client, TokenRequestBuilder tokenRequestBuilder) { + this.oAuthClient = new OAuthClient(new OAuthOkHttpClient(client)); + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public RetryingOAuth(TokenRequestBuilder tokenRequestBuilder) { + this(new OkHttpClient(), tokenRequestBuilder); + } + + /** + @param tokenUrl The token URL to be used for this OAuth2 flow. + Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode". + The value must be an absolute URL. + @param clientId The OAuth2 client ID for the "clientCredentials" flow. + @param clientSecret The OAuth2 client secret for the "clientCredentials" flow. + */ + public RetryingOAuth( + String tokenUrl, + String clientId, + OAuthFlow flow, + String clientSecret, + Map parameters + ) { + this(OAuthClientRequest.tokenLocation(tokenUrl) + .setClientId(clientId) + .setClientSecret(clientSecret)); + setFlow(flow); + if (parameters != null) { + for (String paramName : parameters.keySet()) { + tokenRequestBuilder.setParameter(paramName, parameters.get(paramName)); + } + } + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case accessCode: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case implicit: + tokenRequestBuilder.setGrantType(GrantType.IMPLICIT); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) throws IOException { + return retryingIntercept(chain, true); + } + + private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException { + Request request = chain.request(); + + // If the request already has an authorization (e.g. Basic auth), proceed with the request as is + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // Get the token if it has not yet been acquired + if (getAccessToken() == null) { + updateAccessToken(null); + } + + OAuthClientRequest oAuthRequest; + if (getAccessToken() != null) { + // Build the request + Request.Builder requestBuilder = request.newBuilder(); + + String requestAccessToken = getAccessToken(); + try { + oAuthRequest = + new OAuthBearerClientRequest(request.url().toString()). + setAccessToken(requestAccessToken). + buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + Map headers = oAuthRequest.getHeaders(); + for (String headerName : headers.keySet()) { + requestBuilder.addHeader(headerName, headers.get(headerName)); + } + requestBuilder.url(oAuthRequest.getLocationUri()); + + // Execute the request + Response response = chain.proceed(requestBuilder.build()); + + // 401/403 response codes most likely indicate an expired access token, unless it happens two times in a row + if ( + response != null && + ( response.code() == HttpURLConnection.HTTP_UNAUTHORIZED || + response.code() == HttpURLConnection.HTTP_FORBIDDEN ) && + updateTokenAndRetryOnAuthorizationFailure + ) { + try { + if (updateAccessToken(requestAccessToken)) { + response.body().close(); + return retryingIntercept(chain, false); + } + } catch (Exception e) { + response.body().close(); + throw e; + } + } + return response; + } + else { + return chain.proceed(chain.request()); + } + } + + /* + * Returns true if the access token has been updated + */ + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + try { + OAuthJSONAccessTokenResponse accessTokenResponse = + oAuthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken()); + } + } catch (OAuthSystemException | OAuthProblemException e) { + throw new IOException(e); + } + } + return getAccessToken() == null || !getAccessToken().equals(requestAccessToken); + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + // Applying authorization to parameters is performed in the retryingIntercept method + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + // No implementation necessary + } +} +{{/hasOAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/build.gradle.mustache new file mode 100644 index 00000000000..c97cb873e97 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/build.gradle.mustache @@ -0,0 +1,169 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' +{{#sourceFolder}} +apply plugin: 'java' +{{/sourceFolder}} +apply plugin: 'com.diffplug.spotless' + +group = '{{groupId}}' +version = '{{artifactVersion}}' + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' + classpath 'com.diffplug.spotless:spotless-plugin-gradle:5.17.1' + } +} + +repositories { + mavenCentral() +} +{{#sourceFolder}} +sourceSets { + main.java.srcDirs = ['{{sourceFolder}}'] +} + +{{/sourceFolder}} +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 25 + buildToolsVersion '25.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 25 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + } + } + + 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-publish' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + publishing { + publications { + maven(MavenPublication) { + artifactId = '{{artifactId}}' + from components.java + } + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + jakarta_annotation_version = "1.3.5" +} + +dependencies { + implementation 'io.swagger:swagger-annotations:1.5.24' + implementation "com.google.code.findbugs:jsr305:3.0.2" + implementation 'com.squareup.okhttp3:okhttp:4.9.1' + implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1' + implementation 'com.google.code.gson:gson:2.8.6' + implementation 'io.gsonfire:gson-fire:1.8.4' + {{#openApiNullable}} + implementation 'org.openapitools:jackson-databind-nullable:0.2.1' + {{/openApiNullable}} + {{#hasOAuthMethods}} + implementation group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1' + {{/hasOAuthMethods}} + implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.10' + {{#joda}} + implementation 'joda-time:joda-time:2.9.9' + {{/joda}} + {{#threetenbp}} + implementation 'org.threeten:threetenbp:1.4.3' + {{/threetenbp}} + {{#dynamicOperations}} + implementation 'io.swagger.parser.v3:swagger-parser-v3:2.0.23' + {{/dynamicOperations}} + implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + testImplementation 'junit:junit:4.13.1' + testImplementation 'org.mockito:mockito-core:3.11.2' +} + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} + +// Use spotless plugin to automatically format code, remove unused import, etc +// To apply changes directly to the file, run `gradlew spotlessApply` +// Ref: https://github.com/diffplug/spotless/tree/main/plugin-gradle +spotless { + // comment out below to run spotless as part of the `check` task + enforceCheck false + + format 'misc', { + // define the files (e.g. '*.gradle', '*.md') to apply `misc` to + target '.gitignore' + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithSpaces() // Takes an integer argument if you don't like 4 + endWithNewline() + } + java { + // don't need to set target, it is inferred from java + + // apply a specific flavor of google-java-format + googleJavaFormat('1.8').aosp().reflowLongStrings() + + removeUnusedImports() + importOrder() + } +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/build.sbt.mustache new file mode 100644 index 00000000000..907e8a916ec --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/build.sbt.mustache @@ -0,0 +1,39 @@ +lazy val root = (project in file(".")). + settings( + organization := "{{groupId}}", + name := "{{artifactId}}", + version := "{{artifactVersion}}", + 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.24", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", + "com.google.code.gson" % "gson" % "2.8.6", + "org.apache.commons" % "commons-lang3" % "3.10", + {{#openApiNullable}} + "org.openapitools" % "jackson-databind-nullable" % "0.2.1", + {{/openApiNullable}} + {{#hasOAuthMethods}} + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", + {{/hasOAuthMethods}} + {{#joda}} + "joda-time" % "joda-time" % "2.9.9" % "compile", + {{/joda}} + {{#threetenbp}} + "org.threeten" % "threetenbp" % "1.4.3" % "compile", + {{/threetenbp}} + {{#dynamicOperations}} + "io.swagger.parser.v3" % "swagger-parser-v3" "2.0.23" % "compile" + {{/dynamicOperations}} + "io.gsonfire" % "gson-fire" % "1.8.3" % "compile", + "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", + "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", + "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", + "junit" % "junit" % "4.13.1" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/model.mustache new file mode 100644 index 00000000000..b6b0381a5ce --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/model.mustache @@ -0,0 +1,61 @@ +{{>licenseInfo}} + +package {{package}}; + +{{#useReflectionEqualsHashCode}} +import org.apache.commons.lang3.builder.EqualsBuilder; +import org.apache.commons.lang3.builder.HashCodeBuilder; +{{/useReflectionEqualsHashCode}} +import java.util.Objects; +import java.util.Arrays; +{{#imports}} +import {{import}}; +{{/imports}} +{{#serializableModel}} +import java.io.Serializable; +{{/serializableModel}} +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; +{{#withXml}} +import com.fasterxml.jackson.dataformat.xml.annotation.*; +{{/withXml}} +{{#vendorExtensions.x-has-readonly-properties}} +import com.fasterxml.jackson.annotation.JsonCreator; +{{/vendorExtensions.x-has-readonly-properties}} +{{/jackson}} +{{#withXml}} +import javax.xml.bind.annotation.*; +{{/withXml}} +{{#jsonb}} +import java.lang.reflect.Type; +import javax.json.bind.annotation.JsonbTypeDeserializer; +import javax.json.bind.annotation.JsonbTypeSerializer; +import javax.json.bind.serializer.DeserializationContext; +import javax.json.bind.serializer.JsonbDeserializer; +import javax.json.bind.serializer.JsonbSerializer; +import javax.json.bind.serializer.SerializationContext; +import javax.json.stream.JsonGenerator; +import javax.json.stream.JsonParser; +import javax.json.bind.annotation.JsonbProperty; +{{#vendorExtensions.x-has-readonly-properties}} +import javax.json.bind.annotation.JsonbCreator; +{{/vendorExtensions.x-has-readonly-properties}} +{{/jsonb}} +{{#parcelableModel}} +import android.os.Parcelable; +import android.os.Parcel; +{{/parcelableModel}} +{{#useBeanValidation}} +import javax.validation.constraints.*; +import javax.validation.Valid; +{{/useBeanValidation}} +{{#performBeanValidation}} +import org.hibernate.validator.constraints.*; +{{/performBeanValidation}} + +{{#models}} +{{#model}} +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>oneof_model}}{{/-first}}{{/oneOf}}{{^oneOf}}{{#anyOf}}{{#-first}}{{>anyof_model}}{{/-first}}{{/anyOf}}{{^anyOf}}{{>pojo}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/oneof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/oneof_model.mustache new file mode 100644 index 00000000000..0b7c8b6369e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/oneof_model.mustache @@ -0,0 +1,190 @@ +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import {{invokerPackage}}.JSON; + +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { + private static final Logger log = Logger.getLogger({{classname}}.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!{{classname}}.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes '{{classname}}' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + {{#oneOf}} + final TypeAdapter<{{.}}> adapter{{.}} = gson.getDelegateAdapter(this, TypeToken.get({{.}}.class)); + {{/oneOf}} + + return (TypeAdapter) new TypeAdapter<{{classname}}>() { + @Override + public void write(JsonWriter out, {{classname}} value) throws IOException { + {{#oneOf}} + // check if the actual instance is of the type `{{.}}` + if (value.getActualInstance() instanceof {{.}}) { + JsonObject obj = adapter{{.}}.toJsonTree(({{.}})value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + {{/oneOf}} + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}"); + } + + @Override + public {{classname}} read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + // use discriminator value for faster oneOf lookup + {{classname}} new{{classname}} = new {{classname}}(); + String discriminatorValue = elementAdapter.read(in).getAsJsonObject().get("{{{propertyBaseName}}}").getAsString(); + switch (discriminatorValue) { + {{#mappedModels}} + case "{{{mappingName}}}": + deserialized = adapter{{.}}.fromJsonTree(jsonObject); + new{{classname}}.setActualInstance(deserialized); + return new{{classname}}; + {{/mappedModels}} + default: + log.log(Level.WARNING, String.format("Failed to lookup discriminator value `%s` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue)); + } + + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + int match = 0; + + {{#oneOf}} + // deserialize {{{.}}} + try { + deserialized = adapter{{.}}.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema '{{{.}}}'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema '{{{.}}}'", e); + } + + {{/oneOf}} + if (match == 1) { + {{classname}} ret = new {{classname}}(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for {{classname}}: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public {{classname}}() { + super("oneOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); + } + + {{#oneOf}} + public {{classname}}({{{.}}} o) { + super("oneOf", {{#isNullable}}Boolean.TRUE{{/isNullable}}{{^isNullable}}Boolean.FALSE{{/isNullable}}); + setActualInstance(o); + } + + {{/oneOf}} + static { + {{#oneOf}} + schemas.put("{{{.}}}", new GenericType<{{{.}}}>() { + }); + {{/oneOf}} + } + + @Override + public Map getSchemas() { + return {{classname}}.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}} + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + {{#isNullable}} + if (instance == null) { + super.setActualInstance(instance); + return; + } + + {{/isNullable}} + {{#oneOf}} + if (instance instanceof {{{.}}}) { + super.setActualInstance(instance); + return; + } + + {{/oneOf}} + throw new RuntimeException("Invalid instance type. Must be {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}"); + } + + /** + * Get the actual instance, which can be the following: + * {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}} + * + * @return The actual instance ({{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + {{#oneOf}} + /** + * Get the actual instance of `{{{.}}}`. If the actual instance is not `{{{.}}}`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `{{{.}}}` + * @throws ClassCastException if the instance is not `{{{.}}}` + */ + public {{{.}}} get{{{.}}}() throws ClassCastException { + return ({{{.}}})super.getActualInstance(); + } + + {{/oneOf}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache new file mode 100644 index 00000000000..df9dbc320d4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache @@ -0,0 +1,445 @@ +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * {{description}}{{^description}}{{classname}}{{/description}}{{#isDeprecated}} + * @deprecated{{/isDeprecated}} + */{{#isDeprecated}} +@Deprecated{{/isDeprecated}}{{#description}} +@ApiModel(description = "{{{.}}}"){{/description}} +{{#jackson}} +@JsonPropertyOrder({ +{{#vars}} + {{classname}}.JSON_PROPERTY_{{nameInSnakeCase}}{{^-last}},{{/-last}} +{{/vars}} +}) +@JsonTypeName("{{name}}") +{{/jackson}} +{{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{>xmlAnnotation}} +public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtensions.x-implements}}{{#-first}}implements {{{.}}}{{/-first}}{{^-first}}, {{{.}}}{{/-first}}{{#-last}} {{/-last}}{{/vendorExtensions.x-implements}}{ +{{#serializableModel}} + private static final long serialVersionUID = 1L; + +{{/serializableModel}} + {{#vars}} + {{#isEnum}} + {{^isContainer}} +{{>modelInnerEnum}} + {{/isContainer}} + {{#isContainer}} + {{#mostInnerItems}} +{{>modelInnerEnum}} + {{/mostInnerItems}} + {{/isContainer}} + {{/isEnum}} + {{#gson}} + public static final String SERIALIZED_NAME_{{nameInSnakeCase}} = "{{baseName}}"; + {{/gson}} + {{#jackson}} + public static final String JSON_PROPERTY_{{nameInSnakeCase}} = "{{baseName}}"; + {{/jackson}} + {{#withXml}} + {{#isXmlAttribute}} + @XmlAttribute(name = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/isXmlAttribute}} + {{^isXmlAttribute}} + {{^isContainer}} + @XmlElement({{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}name = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/isContainer}} + {{#isContainer}} + // Is a container wrapped={{isXmlWrapped}} + {{#items}} + // items.name={{name}} items.baseName={{baseName}} items.xmlName={{xmlName}} items.xmlNamespace={{xmlNamespace}} + // items.example={{example}} items.type={{dataType}} + @XmlElement({{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}name = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/items}} + {{#isXmlWrapped}} + @XmlElementWrapper({{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}name = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/isXmlWrapped}} + {{/isContainer}} + {{/isXmlAttribute}} + {{/withXml}} + {{#gson}} + @SerializedName(SERIALIZED_NAME_{{nameInSnakeCase}}) + {{/gson}} + {{#vendorExtensions.x-is-jackson-optional-nullable}} + {{#isContainer}} + private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined(); + {{/isContainer}} + {{^isContainer}} + private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; + {{/isContainer}} + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + {{#isContainer}} + private {{{datatypeWithEnum}}} {{name}}{{#required}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/required}}{{^required}} = null{{/required}}; + {{/isContainer}} + {{^isContainer}} + {{#isDiscriminator}}protected{{/isDiscriminator}}{{^isDiscriminator}}private{{/isDiscriminator}} {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; + {{/isContainer}} + {{/vendorExtensions.x-is-jackson-optional-nullable}} + + {{/vars}} + public {{classname}}() { {{#parent}}{{#parcelableModel}} + super();{{/parcelableModel}}{{/parent}}{{#gson}}{{#discriminator}} + this.{{{discriminatorName}}} = this.getClass().getSimpleName();{{/discriminator}}{{/gson}} + }{{#vendorExtensions.x-has-readonly-properties}}{{^withXml}} + + {{#jsonb}}@JsonbCreator{{/jsonb}}{{#jackson}}@JsonCreator{{/jackson}} + public {{classname}}( + {{#readOnlyVars}} + {{#jsonb}}@JsonbProperty("{{baseName}}"){{/jsonb}}{{#jackson}}@JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}){{/jackson}} {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} + {{/readOnlyVars}} + ) { + this(); + {{#readOnlyVars}} + this.{{name}} = {{name}}; + {{/readOnlyVars}} + }{{/withXml}}{{/vendorExtensions.x-has-readonly-properties}} + {{#vars}} + + {{^isReadOnly}} + public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { + {{#vendorExtensions.x-is-jackson-optional-nullable}}this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}});{{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}}this.{{name}} = {{name}};{{/vendorExtensions.x-is-jackson-optional-nullable}} + return this; + } + {{#isArray}} + + public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { + {{#vendorExtensions.x-is-jackson-optional-nullable}} + if (this.{{name}} == null || !this.{{name}}.isPresent()) { + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}); + } + try { + this.{{name}}.get().add({{name}}Item); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + {{^required}} + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}; + } + {{/required}} + this.{{name}}.add({{name}}Item); + return this; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + } + {{/isArray}} + {{#isMap}} + + public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { + {{#vendorExtensions.x-is-jackson-optional-nullable}} + if (this.{{name}} == null || !this.{{name}}.isPresent()) { + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}); + } + try { + this.{{name}}.get().put(key, {{name}}Item); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + {{^required}} + if (this.{{name}} == null) { + this.{{name}} = {{{defaultValue}}}; + } + {{/required}} + this.{{name}}.put(key, {{name}}Item); + return this; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + } + {{/isMap}} + + {{/isReadOnly}} + /** + {{#description}} + * {{.}} + {{/description}} + {{^description}} + * Get {{name}} + {{/description}} + {{#minimum}} + * minimum: {{.}} + {{/minimum}} + {{#maximum}} + * maximum: {{.}} + {{/maximum}} + * @return {{name}} + {{#deprecated}} + * @deprecated + {{/deprecated}} + **/ +{{#deprecated}} + @Deprecated +{{/deprecated}} +{{#required}} +{{#isNullable}} + @javax.annotation.Nullable +{{/isNullable}} +{{^isNullable}} + @javax.annotation.Nonnull +{{/isNullable}} +{{/required}} +{{^required}} + @javax.annotation.Nullable +{{/required}} +{{#jsonb}} + @JsonbProperty("{{baseName}}") +{{/jsonb}} +{{#useBeanValidation}}{{>beanValidation}}{{/useBeanValidation}} @ApiModelProperty({{#example}}example = "{{{.}}}", {{/example}}{{#required}}required = {{required}}, {{/required}}value = "{{{description}}}") +{{#vendorExtensions.x-extra-annotation}} + {{{vendorExtensions.x-extra-annotation}}} +{{/vendorExtensions.x-extra-annotation}} +{{#vendorExtensions.x-is-jackson-optional-nullable}} + {{!unannotated, Jackson would pick this up automatically and add it *in addition* to the _JsonNullable getter field}} + @JsonIgnore +{{/vendorExtensions.x-is-jackson-optional-nullable}} +{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#jackson}}{{> jackson_annotations}}{{/jackson}}{{/vendorExtensions.x-is-jackson-optional-nullable}} + public {{{datatypeWithEnum}}} {{getter}}() { + {{#vendorExtensions.x-is-jackson-optional-nullable}} + {{#isReadOnly}}{{! A readonly attribute doesn't have setter => jackson will set null directly if explicitly returned by API, so make sure we have an empty JsonNullable}} + if ({{name}} == null) { + {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; + } + {{/isReadOnly}} + return {{name}}.orElse(null); + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + return {{name}}; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + } + + {{#vendorExtensions.x-is-jackson-optional-nullable}} +{{> jackson_annotations}} + public JsonNullable<{{{datatypeWithEnum}}}> {{getter}}_JsonNullable() { + return {{name}}; + } + {{/vendorExtensions.x-is-jackson-optional-nullable}}{{#vendorExtensions.x-is-jackson-optional-nullable}} + @JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}) + {{#isReadOnly}}private{{/isReadOnly}}{{^isReadOnly}}public{{/isReadOnly}} void {{setter}}_JsonNullable(JsonNullable<{{{datatypeWithEnum}}}> {{name}}) { + {{! For getters/setters that have name differing from attribute name, we must include setter (albeit private) for jackson to be able to set the attribute}} + this.{{name}} = {{name}}; + } + {{/vendorExtensions.x-is-jackson-optional-nullable}} + + {{^isReadOnly}} +{{#vendorExtensions.x-setter-extra-annotation}} {{{vendorExtensions.x-setter-extra-annotation}}} +{{/vendorExtensions.x-setter-extra-annotation}}{{#jackson}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{> jackson_annotations}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{/jackson}} public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { + {{#vendorExtensions.x-is-jackson-optional-nullable}} + this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}}); + {{/vendorExtensions.x-is-jackson-optional-nullable}} + {{^vendorExtensions.x-is-jackson-optional-nullable}} + this.{{name}} = {{name}}; + {{/vendorExtensions.x-is-jackson-optional-nullable}} + } + {{/isReadOnly}} + + {{/vars}} + + @Override + public boolean equals(Object o) { + {{#useReflectionEqualsHashCode}} + return EqualsBuilder.reflectionEquals(this, o, false, null, true); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + }{{#hasVars}} + {{classname}} {{classVarName}} = ({{classname}}) o; + return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} && + {{/-last}}{{/vars}}{{#parent}} && + super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} + return {{#parent}}super.equals(o){{/parent}}{{^parent}}true{{/parent}};{{/hasVars}} + {{/useReflectionEqualsHashCode}} + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} + + @Override + public int hashCode() { + {{#useReflectionEqualsHashCode}} + return HashCodeBuilder.reflectionHashCode(this); + {{/useReflectionEqualsHashCode}} + {{^useReflectionEqualsHashCode}} + return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}); + {{/useReflectionEqualsHashCode}} + }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + }{{/vendorExtensions.x-jackson-optional-nullable-helpers}} + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class {{classname}} {\n"); + {{#parent}} + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + {{/parent}} + {{#vars}} + sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{/vars}} + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private{{#jsonb}} static{{/jsonb}} String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +{{#parcelableModel}} + + public void writeToParcel(Parcel out, int flags) { +{{#model}} +{{#isArray}} + out.writeList(this); +{{/isArray}} +{{^isArray}} +{{#parent}} + super.writeToParcel(out, flags); +{{/parent}} +{{#vars}} + out.writeValue({{name}}); +{{/vars}} +{{/isArray}} +{{/model}} + } + + {{classname}}(Parcel in) { +{{#isArray}} + in.readTypedList(this, {{arrayModelType}}.CREATOR); +{{/isArray}} +{{^isArray}} +{{#parent}} + super(in); +{{/parent}} +{{#vars}} +{{#isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue(null); +{{/isPrimitiveType}} +{{^isPrimitiveType}} + {{name}} = ({{{datatypeWithEnum}}})in.readValue({{complexType}}.class.getClassLoader()); +{{/isPrimitiveType}} +{{/vars}} +{{/isArray}} + } + + public int describeContents() { + return 0; + } + + public static final Parcelable.Creator<{{classname}}> CREATOR = new Parcelable.Creator<{{classname}}>() { + public {{classname}} createFromParcel(Parcel in) { +{{#model}} +{{#isArray}} + {{classname}} result = new {{classname}}(); + result.addAll(in.readArrayList({{arrayModelType}}.class.getClassLoader())); + return result; +{{/isArray}} +{{^isArray}} + return new {{classname}}(in); +{{/isArray}} +{{/model}} + } + public {{classname}}[] newArray(int size) { + return new {{classname}}[size]; + } + }; +{{/parcelableModel}} + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + {{#allVars}} + openapiFields.add("{{baseName}}"); + {{/allVars}} + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + {{#requiredVars}} + openapiRequiredFields.add("{{baseName}}"); + {{/requiredVars}} + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!{{classname}}.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes '{{classname}}' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter<{{classname}}> thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get({{classname}}.class)); + + return (TypeAdapter) new TypeAdapter<{{classname}}>() { + @Override + public void write(JsonWriter out, {{classname}} value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public {{classname}} read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!{{classname}}.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `{{classname}}` properties"); + } + } + + {{#requiredVars}} + {{#-first}} + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : {{classname}}.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + {{/-first}} + {{/requiredVars}} + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pom.mustache new file mode 100644 index 00000000000..5d33c6ce25b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pom.mustache @@ -0,0 +1,420 @@ + + 4.0.0 + {{groupId}} + {{artifactId}} + jar + {{artifactId}} + {{artifactVersion}} + {{artifactUrl}} + {{artifactDescription}} + + {{scmConnection}} + {{scmDeveloperConnection}} + {{scmUrl}} + +{{#parentOverridden}} + + {{{parentGroupId}}} + {{{parentArtifactId}}} + {{{parentVersion}}} + +{{/parentOverridden}} + + + + {{licenseName}} + {{licenseUrl}} + repo + + + + + + {{developerName}} + {{developerEmail}} + {{developerOrganization}} + {{developerOrganizationUrl}} + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 10 + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.0 + + + + test-jar + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.2.0 + + + add_sources + generate-sources + + add-source + + + + {{{sourceFolder}}} + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.3.1 + + + attach-javadocs + + jar + + + + + none + + + http.response.details + a + Http Response Details: + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.2.0 + + + attach-sources + + jar-no-fork + + + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + + + + + .gitignore + + + + + + true + 4 + + + + + + + + + + 1.8 + + true + + + + + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.0.1 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + com.squareup.okhttp3 + okhttp + ${okhttp-version} + + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + io.gsonfire + gson-fire + ${gson-fire-version} + + {{#hasOAuthMethods}} + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + 1.0.1 + + {{/hasOAuthMethods}} + + org.apache.commons + commons-lang3 + ${commons-lang3-version} + + {{#joda}} + + joda-time + joda-time + ${jodatime-version} + + {{/joda}} + {{#threetenbp}} + + org.threeten + threetenbp + ${threetenbp-version} + + {{/threetenbp}} + {{#dynamicOperations}} + + io.swagger.parser.v3 + swagger-parser-v3 + 2.0.28 + + {{/dynamicOperations}} + {{#useBeanValidation}} + + + jakarta.validation + jakarta.validation-api + ${beanvalidation-version} + provided + + {{/useBeanValidation}} + {{#performBeanValidation}} + + + org.hibernate + hibernate-validator + 5.4.3.Final + + + jakarta.el + jakarta.el-api + ${jakarta.el-version} + + {{/performBeanValidation}} + {{#parcelableModel}} + + + com.google.android + android + 4.1.1.4 + provided + + {{/parcelableModel}} + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation-version} + provided + + {{#openApiNullable}} + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + {{/openApiNullable}} + + javax.ws.rs + jsr311-api + 1.1.1 + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + + junit + junit + ${junit-version} + test + + + org.mockito + mockito-core + 3.12.4 + test + + + + 1.8 + ${java.version} + ${java.version} + 1.8.5 + 1.6.3 + 4.9.2 + 2.8.8 + 3.12.0 + {{#openApiNullable}} + 0.2.1 + {{/openApiNullable}} + {{#joda}} + 2.10.9 + {{/joda}} + {{#threetenbp}} + 1.5.0 + {{/threetenbp}} + 1.3.5 +{{#performBeanValidation}} + 3.0.3 +{{/performBeanValidation}} +{{#useBeanValidation}} + 2.0.2 +{{/useBeanValidation}} + 4.13.2 + UTF-8 + 2.17.3 + + diff --git a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml new file mode 100644 index 00000000000..92b32a47679 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature-okhttp-gson.yaml @@ -0,0 +1,2145 @@ +openapi: 3.0.0 +info: + description: >- + This spec is mainly for testing Petstore server and contains fake endpoints, + models. Please do not use this for any other purpose. Special characters: " + \ + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /foo: + get: + responses: + default: + description: response + content: + application/json: + schema: + type: object + properties: + string: + $ref: '#/components/schemas/Foo' + /pet: + servers: + - url: 'http://petstore.swagger.io/v2' + - url: 'http://path-server-test.petstore.local/v2' + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '405': + description: Invalid input + security: + - http_signature_test: [] + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - http_signature_test: [] + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - http_signature_test: [] + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - http_signature_test: [] + - petstore_auth: + - 'write:pets' + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{order_id}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: order_id + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: order_id + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + /fake_classname_test: + patch: + tags: + - 'fake_classname_tags 123#$%^' + summary: To test class name in snake case + description: To test class name in snake case + operationId: testClassname + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + security: + - api_key_query: [] + requestBody: + $ref: '#/components/requestBodies/Client' + /fake: + patch: + tags: + - fake + summary: To test "client" model + description: To test "client" model + operationId: testClientModel + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + requestBody: + $ref: '#/components/requestBodies/Client' + get: + tags: + - fake + summary: To test enum parameters + description: To test enum parameters + operationId: testEnumParameters + parameters: + - name: enum_header_string_array + in: header + description: Header parameter enum test (string array) + schema: + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + - name: enum_header_string + in: header + description: Header parameter enum test (string) + schema: + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + - name: enum_query_string_array + in: query + description: Query parameter enum test (string array) + schema: + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + - name: enum_query_string + in: query + description: Query parameter enum test (string) + schema: + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + - name: enum_query_integer + in: query + description: Query parameter enum test (double) + schema: + type: integer + format: int32 + enum: + - 1 + - -2 + - name: enum_query_double + in: query + description: Query parameter enum test (double) + schema: + type: number + format: double + enum: + - 1.1 + - -1.2 + responses: + '400': + description: Invalid request + '404': + description: Not found + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + enum_form_string: + description: Form parameter enum test (string) + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + post: + tags: + - fake + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - http_basic_test: [] + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + integer: + description: None + type: integer + minimum: 10 + maximum: 100 + int32: + description: None + type: integer + format: int32 + minimum: 20 + maximum: 200 + int64: + description: None + type: integer + format: int64 + number: + description: None + type: number + minimum: 32.1 + maximum: 543.2 + float: + description: None + type: number + format: float + maximum: 987.6 + double: + description: None + type: number + format: double + minimum: 67.8 + maximum: 123.4 + string: + description: None + type: string + pattern: '/[a-z]/i' + pattern_without_delimiter: + description: None + type: string + pattern: '^[A-Z].*' + byte: + description: None + type: string + format: byte + binary: + description: None + type: string + format: binary + date: + description: None + type: string + format: date + dateTime: + description: None + type: string + format: date-time + default: '2010-02-01T10:20:10.11111+01:00' + example: '2020-02-02T20:20:20.22222Z' + password: + description: None + type: string + format: password + minLength: 10 + maxLength: 64 + callback: + description: None + type: string + required: + - number + - double + - pattern_without_delimiter + - byte + delete: + tags: + - fake + security: + - bearer_test: [] + summary: Fake endpoint to test group parameters (optional) + description: Fake endpoint to test group parameters (optional) + operationId: testGroupParameters + x-group-parameters: true + parameters: + - name: required_string_group + in: query + description: Required String in group parameters + required: true + schema: + type: integer + - name: required_boolean_group + in: header + description: Required Boolean in group parameters + required: true + schema: + type: boolean + - name: required_int64_group + in: query + description: Required Integer in group parameters + required: true + schema: + type: integer + format: int64 + - name: string_group + in: query + description: String in group parameters + schema: + type: integer + - name: boolean_group + in: header + description: Boolean in group parameters + schema: + type: boolean + - name: int64_group + in: query + description: Integer in group parameters + schema: + type: integer + format: int64 + responses: + '400': + description: Someting wrong + /fake/outer/number: + post: + tags: + - fake + description: Test serialization of outer number types + operationId: fakeOuterNumberSerialize + responses: + '200': + description: Output number + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterNumber' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterNumber' + description: Input number as post body + /fake/outer/string: + post: + tags: + - fake + description: Test serialization of outer string types + operationId: fakeOuterStringSerialize + responses: + '200': + description: Output string + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterString' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterString' + description: Input string as post body + /fake/outer/boolean: + post: + tags: + - fake + description: Test serialization of outer boolean types + operationId: fakeOuterBooleanSerialize + responses: + '200': + description: Output boolean + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterBoolean' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Input boolean as post body + /fake/outer/composite: + post: + tags: + - fake + description: Test serialization of object with outer number type + operationId: fakeOuterCompositeSerialize + responses: + '200': + description: Output composite + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterComposite' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterComposite' + description: Input composite as post body + /fake/jsonFormData: + get: + tags: + - fake + summary: test json serialization of form data + description: '' + operationId: testJsonFormData + responses: + '200': + description: successful operation + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + /fake/inline-additionalProperties: + post: + tags: + - fake + summary: test inline additionalProperties + description: '' + operationId: testInlineAdditionalProperties + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + type: object + additionalProperties: + type: string + description: request body + required: true + /fake/body-with-query-params: + put: + tags: + - fake + operationId: testBodyWithQueryParams + parameters: + - name: query + in: query + required: true + schema: + type: string + responses: + '200': + description: Success + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + /another-fake/dummy: + patch: + tags: + - $another-fake? + summary: To test special tags + description: To test special tags and operation ID starting with number + operationId: '123_test_@#$%_special_tags' + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + requestBody: + $ref: '#/components/requestBodies/Client' + /fake/body-with-file-schema: + put: + tags: + - fake + description: >- + For this test, the body for this request much reference a schema named + `File`. + operationId: testBodyWithFileSchema + responses: + '200': + description: Success + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FileSchemaTestClass' + required: true + /fake/test-query-parameters: + put: + tags: + - fake + description: To test the collection format in query parameters + operationId: testQueryParameterCollectionFormat + parameters: + - name: pipe + in: query + required: true + schema: + type: array + items: + type: string + - name: ioutil + in: query + required: true + style: form + explode: false + schema: + type: array + items: + type: string + - name: http + in: query + required: true + style: spaceDelimited + schema: + type: array + items: + type: string + - name: url + in: query + required: true + style: form + explode: false + schema: + type: array + items: + type: string + - name: context + in: query + required: true + explode: true + schema: + type: array + items: + type: string + responses: + "200": + description: Success + '/fake/{petId}/uploadImageWithRequiredFile': + post: + tags: + - pet + summary: uploads an image (required) + description: '' + operationId: uploadFileWithRequiredFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + type: string + format: binary + required: + - requiredFile + /fake/health: + get: + tags: + - fake + summary: Health check endpoint + responses: + 200: + description: The instance started successfully + content: + application/json: + schema: + $ref: '#/components/schemas/HealthCheckResult' + /fake/array-of-enums: + get: + tags: + - fake + summary: Array of Enums + operationId: getArrayOfEnums + responses: + 200: + description: Got named array of enums + content: + application/json: + schema: + $ref: '#/components/schemas/ArrayOfEnums' +servers: + - url: 'http://{server}.swagger.io:{port}/v2' + description: petstore server + variables: + server: + enum: + - 'petstore' + - 'qa-petstore' + - 'dev-petstore' + default: 'petstore' + port: + enum: + - 80 + - 8080 + default: 80 + - url: https://localhost:8080/{version} + description: The local server + variables: + version: + enum: + - 'v1' + - 'v2' + default: 'v2' + - url: https://127.0.0.1/no_variable + description: The local server without variables +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + examples: + simple-list: + summary: Simple list example + description: Should not get into code examples + value: + - username: foo + - username: bar + description: List of user object + required: true + Client: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + api_key_query: + type: apiKey + name: api_key_query + in: query + http_basic_test: + type: http + scheme: basic + bearer_test: + type: http + scheme: bearer + bearerFormat: JWT + http_signature_test: + # Test the 'HTTP signature' security scheme. + # Each HTTP request is cryptographically signed as specified + # in https://datatracker.ietf.org/doc/draft-cavage-http-signatures/ + type: http + scheme: signature + schemas: + Foo: + type: object + properties: + bar: + $ref: '#/components/schemas/Bar' + Bar: + type: string + default: bar + Order: + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + example: '2020-02-02T20:20:20.000222Z' + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + type: object + required: + - name + properties: + id: + type: integer + format: int64 + name: + type: string + default: default-name + xml: + name: Category + User: + type: object + properties: + id: + type: integer + format: int64 + x-is-unique: true + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + objectWithNoDeclaredProps: + type: object + # Note: the 'additionalProperties' keyword is not specified, which is + # equivalent to allowing undeclared properties of any type. + description: test code generation for objects + Value must be a map of strings to values. It cannot be the 'null' value. + objectWithNoDeclaredPropsNullable: + type: object + # Note: the 'additionalProperties' keyword is not specified, which is + # equivalent to allowing undeclared properties of any type. + description: test code generation for nullable objects. + Value must be a map of strings to values or the 'null' value. + nullable: true + anyTypeProp: + description: test code generation for any type + Here the 'type' attribute is not specified, which means the value can be anything, + including the null value, string, number, boolean, array or object. + See https://github.com/OAI/OpenAPI-Specification/issues/1389 + # TODO: this should be supported, currently there are some issues in the code generation. + #anyTypeExceptNullProp: + # description: any type except 'null' + # Here the 'type' attribute is not specified, which means the value can be anything, + # including the null value, string, number, boolean, array or object. + # not: + # type: 'null' + anyTypePropNullable: + description: test code generation for any type + Here the 'type' attribute is not specified, which means the value can be anything, + including the null value, string, number, boolean, array or object. + The 'nullable' attribute does not change the allowed values. + nullable: true + xml: + name: User + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + x-is-unique: true + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + Return: + description: Model for testing reserved words + properties: + return: + type: integer + format: int32 + xml: + name: Return + Name: + description: Model for testing model name same as property name + required: + - name + properties: + name: + type: integer + format: int32 + snake_case: + readOnly: true + type: integer + format: int32 + property: + type: string + 123Number: + type: integer + readOnly: true + xml: + name: Name + 200_response: + description: Model for testing model name starting with number + properties: + name: + type: integer + format: int32 + class: + type: string + xml: + name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - type: object + properties: + breed: + type: string + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - $ref: '#/components/schemas/Address' + - type: object + properties: + declawed: + type: boolean + Address: + type: object + additionalProperties: + type: integer + Animal: + type: object + discriminator: + propertyName: className + required: + - className + properties: + className: + type: string + color: + type: string + default: red + AnimalFarm: + type: array + items: + $ref: '#/components/schemas/Animal' + format_test: + type: object + required: + - number + - byte + - date + - password + properties: + integer: + type: integer + maximum: 100 + minimum: 10 + multipleOf: 2 + int32: + type: integer + format: int32 + maximum: 200 + minimum: 20 + int64: + type: integer + format: int64 + number: + maximum: 543.2 + minimum: 32.1 + type: number + multipleOf: 32.5 + float: + type: number + format: float + maximum: 987.6 + minimum: 54.3 + double: + type: number + format: double + maximum: 123.4 + minimum: 67.8 + decimal: + type: string + format: number + string: + type: string + pattern: '/[a-z]/i' + byte: + type: string + format: byte + binary: + type: string + format: binary + date: + type: string + format: date + example: '2020-02-02' + dateTime: + type: string + format: date-time + example: '2007-12-03T10:15:30+01:00' + uuid: + type: string + format: uuid + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + password: + type: string + format: password + maxLength: 64 + minLength: 10 + pattern_with_digits: + description: A string that is a 10 digit number. Can have leading zeros. + type: string + pattern: '^\d{10}$' + pattern_with_digits_and_delimiter: + description: A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + type: string + pattern: '/^image_\d{1,3}$/i' + EnumClass: + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + Enum_Test: + type: object + required: + - enum_string_required + properties: + enum_string: + type: string + enum: + - UPPER + - lower + - '' + enum_string_required: + type: string + enum: + - UPPER + - lower + - '' + enum_integer: + type: integer + format: int32 + enum: + - 1 + - -1 + enum_integer_only: + type: integer + enum: + - 2 + - -2 + enum_number: + type: number + format: double + enum: + - 1.1 + - -1.2 + outerEnum: + $ref: '#/components/schemas/OuterEnum' + outerEnumInteger: + $ref: '#/components/schemas/OuterEnumInteger' + outerEnumDefaultValue: + $ref: '#/components/schemas/OuterEnumDefaultValue' + outerEnumIntegerDefaultValue: + $ref: '#/components/schemas/OuterEnumIntegerDefaultValue' + AdditionalPropertiesClass: + type: object + properties: + map_property: + type: object + additionalProperties: + type: string + map_of_map_property: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + anytype_1: {} + map_with_undeclared_properties_anytype_1: + type: object + map_with_undeclared_properties_anytype_2: + type: object + properties: {} + map_with_undeclared_properties_anytype_3: + type: object + additionalProperties: true + empty_map: + type: object + description: an object with no declared properties and no undeclared + properties, hence it's an empty map. + additionalProperties: false + map_with_undeclared_properties_string: + type: object + additionalProperties: + type: string + MixedPropertiesAndAdditionalPropertiesClass: + type: object + properties: + uuid: + type: string + format: uuid + dateTime: + type: string + format: date-time + map: + type: object + additionalProperties: + $ref: '#/components/schemas/Animal' + List: + type: object + properties: + 123-list: + type: string + Client: + type: object + properties: + client: + type: string + ReadOnlyFirst: + type: object + properties: + bar: + type: string + readOnly: true + baz: + type: string + hasOnlyReadOnly: + type: object + properties: + bar: + type: string + readOnly: true + foo: + type: string + readOnly: true + Capitalization: + type: object + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: | + Name of the pet + type: string + MapTest: + type: object + properties: + map_map_of_string: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + map_of_enum_string: + type: object + additionalProperties: + type: string + enum: + - UPPER + - lower + direct_map: + type: object + additionalProperties: + type: boolean + indirect_map: + $ref: '#/components/schemas/StringBooleanMap' + ArrayTest: + type: object + properties: + array_of_string: + type: array + items: + type: string + array_array_of_integer: + type: array + items: + type: array + items: + type: integer + format: int64 + array_array_of_model: + type: array + items: + type: array + items: + $ref: '#/components/schemas/ReadOnlyFirst' + NumberOnly: + type: object + properties: + JustNumber: + type: number + ArrayOfNumberOnly: + type: object + properties: + ArrayNumber: + type: array + items: + type: number + ArrayOfArrayOfNumberOnly: + type: object + properties: + ArrayArrayNumber: + type: array + items: + type: array + items: + type: number + EnumArrays: + type: object + properties: + just_symbol: + type: string + enum: + - '>=' + - $ + array_enum: + type: array + items: + type: string + enum: + - fish + - crab + OuterEnum: + nullable: true + type: string + enum: + - placed + - approved + - delivered + OuterEnumInteger: + type: integer + enum: + - 0 + - 1 + - 2 + OuterEnumDefaultValue: + type: string + enum: + - placed + - approved + - delivered + default: placed + OuterEnumIntegerDefaultValue: + type: integer + enum: + - 0 + - 1 + - 2 + default: 0 + OuterComposite: + type: object + properties: + my_number: + $ref: '#/components/schemas/OuterNumber' + my_string: + $ref: '#/components/schemas/OuterString' + my_boolean: + $ref: '#/components/schemas/OuterBoolean' + OuterNumber: + type: number + OuterString: + type: string + OuterBoolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + StringBooleanMap: + additionalProperties: + type: boolean + FileSchemaTestClass: + type: object + properties: + file: + $ref: '#/components/schemas/File' + files: + type: array + items: + $ref: '#/components/schemas/File' + File: + type: object + description: Must be named `File` for test. + properties: + sourceURI: + description: Test capitalization + type: string + _special_model.name_: + properties: + '$special[property.name]': + type: integer + format: int64 + '_special_model.name_': + type: string + xml: + name: '$special[model.name]' + HealthCheckResult: + type: object + properties: + NullableMessage: + nullable: true + type: string + description: Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + NullableClass: + type: object + properties: + integer_prop: + type: integer + nullable: true + number_prop: + type: number + nullable: true + boolean_prop: + type: boolean + nullable: true + string_prop: + type: string + nullable: true + date_prop: + type: string + format: date + nullable: true + datetime_prop: + type: string + format: date-time + nullable: true + array_nullable_prop: + type: array + nullable: true + items: + type: object + array_and_items_nullable_prop: + type: array + nullable: true + items: + type: object + nullable: true + array_items_nullable: + type: array + items: + type: object + nullable: true + object_nullable_prop: + type: object + nullable: true + additionalProperties: + type: object + object_and_items_nullable_prop: + type: object + nullable: true + additionalProperties: + type: object + nullable: true + object_items_nullable: + type: object + additionalProperties: + type: object + nullable: true + additionalProperties: + type: object + nullable: true + fruit: + properties: + color: + type: string + oneOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + # Below additionalProperties is set to false to validate the use + # case when a composed schema has additionalProperties set to false. + additionalProperties: false + apple: + type: object + properties: + cultivar: + type: string + pattern: ^[a-zA-Z\s]*$ + origin: + type: string + pattern: /^[A-Z\s]*$/i + nullable: true + banana: + type: object + properties: + lengthCm: + type: number + mammal: + oneOf: + - $ref: '#/components/schemas/whale' + - $ref: '#/components/schemas/zebra' + - $ref: '#/components/schemas/Pig' + discriminator: + propertyName: className + whale: + type: object + properties: + hasBaleen: + type: boolean + hasTeeth: + type: boolean + className: + type: string + required: + - className + zebra: + type: object + properties: + type: + type: string + enum: + - plains + - mountain + - grevys + className: + type: string + required: + - className + additionalProperties: true + Pig: + oneOf: + - $ref: '#/components/schemas/BasquePig' + - $ref: '#/components/schemas/DanishPig' + discriminator: + propertyName: className + BasquePig: + type: object + properties: + className: + type: string + required: + - className + DanishPig: + type: object + properties: + className: + type: string + required: + - className + gmFruit: + properties: + color: + type: string + anyOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + additionalProperties: false + fruitReq: + oneOf: + - type: 'null' + - $ref: '#/components/schemas/appleReq' + - $ref: '#/components/schemas/bananaReq' + additionalProperties: false + appleReq: + type: object + properties: + cultivar: + type: string + mealy: + type: boolean + required: + - cultivar + additionalProperties: false + bananaReq: + type: object + properties: + lengthCm: + type: number + sweet: + type: boolean + required: + - lengthCm + additionalProperties: false + # go-experimental is unable to make Triangle and Quadrilateral models + # correctly https://github.com/OpenAPITools/openapi-generator/issues/6149 + Drawing: + type: object + properties: + mainShape: + # A property whose value is a 'oneOf' type, and the type is referenced instead + # of being defined inline. The value cannot be null. + $ref: '#/components/schemas/Shape' + shapeOrNull: + # A property whose value is a 'oneOf' type, and the type is referenced instead + # of being defined inline. The value may be null because ShapeOrNull has 'null' + # type as a child schema of 'oneOf'. + $ref: '#/components/schemas/ShapeOrNull' + nullableShape: + # A property whose value is a 'oneOf' type, and the type is referenced instead + # of being defined inline. The value may be null because NullableShape has the + # 'nullable: true' attribute. For this specific scenario this is exactly the + # same thing as 'shapeOrNull'. + $ref: '#/components/schemas/NullableShape' + shapes: + type: array + items: + $ref: '#/components/schemas/Shape' + additionalProperties: + # Here the additional properties are specified using a referenced schema. + # This is just to validate the generated code works when using $ref + # under 'additionalProperties'. + $ref: '#/components/schemas/fruit' + Shape: + oneOf: + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + discriminator: + propertyName: shapeType + ShapeOrNull: + description: The value may be a shape or the 'null' value. + This is introduced in OAS schema >= 3.1. + oneOf: + - type: 'null' + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + discriminator: + propertyName: shapeType + NullableShape: + description: The value may be a shape or the 'null' value. + The 'nullable' attribute was introduced in OAS schema >= 3.0 + and has been deprecated in OAS schema >= 3.1. + oneOf: + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + discriminator: + propertyName: shapeType + nullable: true + ShapeInterface: + properties: + shapeType: + type: string + required: + - shapeType + TriangleInterface: + properties: + triangleType: + type: string + required: + - triangleType + Triangle: + oneOf: + - $ref: '#/components/schemas/EquilateralTriangle' + - $ref: '#/components/schemas/IsoscelesTriangle' + - $ref: '#/components/schemas/ScaleneTriangle' + discriminator: + propertyName: triangleType + # Note: the 'additionalProperties' keyword is not specified, which is + # equivalent to allowing undeclared properties of any type. + EquilateralTriangle: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/TriangleInterface' + IsoscelesTriangle: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/TriangleInterface' + additionalProperties: false + ScaleneTriangle: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/TriangleInterface' + QuadrilateralInterface: + properties: + quadrilateralType: + type: string + required: + - quadrilateralType + Quadrilateral: + oneOf: + - $ref: '#/components/schemas/SimpleQuadrilateral' + - $ref: '#/components/schemas/ComplexQuadrilateral' + discriminator: + propertyName: quadrilateralType + SimpleQuadrilateral: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/QuadrilateralInterface' + ComplexQuadrilateral: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/QuadrilateralInterface' + GrandparentAnimal: + type: object + required: + - pet_type + properties: + pet_type: + type: string + discriminator: + propertyName: pet_type + ParentPet: + type: object + allOf: + - $ref: '#/components/schemas/GrandparentAnimal' + #ChildCat: + # allOf: + # - $ref: '#/components/schemas/ParentPet' + # - type: object + # properties: + # name: + # type: string + # pet_type: + # x-enum-as-string: true + # type: string + # enum: + # - ChildCat + # default: ChildCat + ArrayOfEnums: + type: array + items: + $ref: '#/components/schemas/OuterEnum' + DateTimeTest: + type: string + default: '2010-01-01T10:10:10.000111+01:00' + example: '2010-01-01T10:10:10.000111+01:00' + format: date-time + DeprecatedObject: + type: object + deprecated: true + properties: + name: + type: string + ObjectWithDeprecatedFields: + type: object + properties: + uuid: + type: string + id: + type: number + deprecated: true + deprecatedRef: + $ref: '#/components/schemas/DeprecatedObject' + bars: + type: array + deprecated: true + items: + $ref: '#/components/schemas/Bar' diff --git a/pom.xml b/pom.xml index 01a361c803e..bc359854717 100644 --- a/pom.xml +++ b/pom.xml @@ -1299,6 +1299,7 @@ samples/openapi3/client/petstore/java/jersey2-java8 samples/client/others/java/okhttp-gson-streaming samples/client/petstore/java/okhttp-gson + samples/client/petstore/java/okhttp-gson-nextgen samples/client/petstore/java/retrofit2 samples/client/petstore/java/retrofit2rx2 samples/client/petstore/java/retrofit2rx3 diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java new file mode 100644 index 00000000000..ddda27d5fed --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -0,0 +1,149 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.openapitools.client.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 nullable + * + * @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/client/petstore/java/okhttp-gson-nextgen/.gitignore b/samples/client/petstore/java/okhttp-gson-nextgen/.gitignore new file mode 100644 index 00000000000..a530464afa1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator-ignore b/samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator-ignore new file mode 100644 index 00000000000..6ba435b5655 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator-ignore @@ -0,0 +1,14 @@ +# OpenAPI Generator Ignore +# These tests are "live" tests and should not be overwritten +src/test/java/org/openapitools/client/StringUtilTest.java +src/test/java/org/openapitools/client/ApiClientTest.java +src/test/java/org/openapitools/client/ConfigurationTest.java +src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java +src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java +src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java +src/test/java/org/openapitools/client/model/EnumValueTest.java +src/test/java/org/openapitools/client/model/PetTest.java +src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java +src/test/java/org/openapitools/client/JSONTest.java +src/test/java/org/openapitools/client/api/PetApiTest.java + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator/FILES b/samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator/FILES new file mode 100644 index 00000000000..39148a7980a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator/FILES @@ -0,0 +1,195 @@ +.gitignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/AdditionalPropertiesClass.md +docs/Animal.md +docs/AnotherFakeApi.md +docs/Apple.md +docs/AppleReq.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Banana.md +docs/BananaReq.md +docs/BasquePig.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/ComplexQuadrilateral.md +docs/DanishPig.md +docs/DefaultApi.md +docs/DeprecatedObject.md +docs/Dog.md +docs/DogAllOf.md +docs/Drawing.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/EquilateralTriangle.md +docs/FakeApi.md +docs/FakeClassnameTags123Api.md +docs/FileSchemaTestClass.md +docs/Foo.md +docs/FormatTest.md +docs/Fruit.md +docs/FruitReq.md +docs/GmFruit.md +docs/GrandparentAnimal.md +docs/HasOnlyReadOnly.md +docs/HealthCheckResult.md +docs/InlineResponseDefault.md +docs/IsoscelesTriangle.md +docs/Mammal.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/ModelApiResponse.md +docs/ModelReturn.md +docs/Name.md +docs/NullableClass.md +docs/NullableShape.md +docs/NumberOnly.md +docs/ObjectWithDeprecatedFields.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/OuterEnumDefaultValue.md +docs/OuterEnumInteger.md +docs/OuterEnumIntegerDefaultValue.md +docs/ParentPet.md +docs/Pet.md +docs/PetApi.md +docs/Pig.md +docs/Quadrilateral.md +docs/QuadrilateralInterface.md +docs/ReadOnlyFirst.md +docs/ScaleneTriangle.md +docs/Shape.md +docs/ShapeInterface.md +docs/ShapeOrNull.md +docs/SimpleQuadrilateral.md +docs/SpecialModelName.md +docs/StoreApi.md +docs/Tag.md +docs/Triangle.md +docs/TriangleInterface.md +docs/User.md +docs/UserApi.md +docs/Whale.md +docs/Zebra.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/ApiCallback.java +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/GzipRequestInterceptor.java +src/main/java/org/openapitools/client/JSON.java +src/main/java/org/openapitools/client/Pair.java +src/main/java/org/openapitools/client/ProgressRequestBody.java +src/main/java/org/openapitools/client/ProgressResponseBody.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/AnotherFakeApi.java +src/main/java/org/openapitools/client/api/DefaultApi.java +src/main/java/org/openapitools/client/api/FakeApi.java +src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +src/main/java/org/openapitools/client/api/PetApi.java +src/main/java/org/openapitools/client/api/StoreApi.java +src/main/java/org/openapitools/client/api/UserApi.java +src/main/java/org/openapitools/client/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/auth/OAuth.java +src/main/java/org/openapitools/client/auth/OAuthFlow.java +src/main/java/org/openapitools/client/auth/OAuthOkHttpClient.java +src/main/java/org/openapitools/client/auth/RetryingOAuth.java +src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +src/main/java/org/openapitools/client/model/Animal.java +src/main/java/org/openapitools/client/model/Apple.java +src/main/java/org/openapitools/client/model/AppleReq.java +src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +src/main/java/org/openapitools/client/model/ArrayTest.java +src/main/java/org/openapitools/client/model/Banana.java +src/main/java/org/openapitools/client/model/BananaReq.java +src/main/java/org/openapitools/client/model/BasquePig.java +src/main/java/org/openapitools/client/model/Capitalization.java +src/main/java/org/openapitools/client/model/Cat.java +src/main/java/org/openapitools/client/model/CatAllOf.java +src/main/java/org/openapitools/client/model/Category.java +src/main/java/org/openapitools/client/model/ClassModel.java +src/main/java/org/openapitools/client/model/Client.java +src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java +src/main/java/org/openapitools/client/model/DanishPig.java +src/main/java/org/openapitools/client/model/DeprecatedObject.java +src/main/java/org/openapitools/client/model/Dog.java +src/main/java/org/openapitools/client/model/DogAllOf.java +src/main/java/org/openapitools/client/model/Drawing.java +src/main/java/org/openapitools/client/model/EnumArrays.java +src/main/java/org/openapitools/client/model/EnumClass.java +src/main/java/org/openapitools/client/model/EnumTest.java +src/main/java/org/openapitools/client/model/EquilateralTriangle.java +src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +src/main/java/org/openapitools/client/model/Foo.java +src/main/java/org/openapitools/client/model/FormatTest.java +src/main/java/org/openapitools/client/model/Fruit.java +src/main/java/org/openapitools/client/model/FruitReq.java +src/main/java/org/openapitools/client/model/GmFruit.java +src/main/java/org/openapitools/client/model/GrandparentAnimal.java +src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +src/main/java/org/openapitools/client/model/HealthCheckResult.java +src/main/java/org/openapitools/client/model/InlineResponseDefault.java +src/main/java/org/openapitools/client/model/IsoscelesTriangle.java +src/main/java/org/openapitools/client/model/Mammal.java +src/main/java/org/openapitools/client/model/MapTest.java +src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +src/main/java/org/openapitools/client/model/Model200Response.java +src/main/java/org/openapitools/client/model/ModelApiResponse.java +src/main/java/org/openapitools/client/model/ModelReturn.java +src/main/java/org/openapitools/client/model/Name.java +src/main/java/org/openapitools/client/model/NullableClass.java +src/main/java/org/openapitools/client/model/NullableShape.java +src/main/java/org/openapitools/client/model/NumberOnly.java +src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +src/main/java/org/openapitools/client/model/Order.java +src/main/java/org/openapitools/client/model/OuterComposite.java +src/main/java/org/openapitools/client/model/OuterEnum.java +src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java +src/main/java/org/openapitools/client/model/OuterEnumInteger.java +src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java +src/main/java/org/openapitools/client/model/ParentPet.java +src/main/java/org/openapitools/client/model/Pet.java +src/main/java/org/openapitools/client/model/Pig.java +src/main/java/org/openapitools/client/model/Quadrilateral.java +src/main/java/org/openapitools/client/model/QuadrilateralInterface.java +src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +src/main/java/org/openapitools/client/model/ScaleneTriangle.java +src/main/java/org/openapitools/client/model/Shape.java +src/main/java/org/openapitools/client/model/ShapeInterface.java +src/main/java/org/openapitools/client/model/ShapeOrNull.java +src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java +src/main/java/org/openapitools/client/model/SpecialModelName.java +src/main/java/org/openapitools/client/model/Tag.java +src/main/java/org/openapitools/client/model/Triangle.java +src/main/java/org/openapitools/client/model/TriangleInterface.java +src/main/java/org/openapitools/client/model/User.java +src/main/java/org/openapitools/client/model/Whale.java +src/main/java/org/openapitools/client/model/Zebra.java diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator/VERSION new file mode 100644 index 00000000000..4077803655c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/.travis.yml b/samples/client/petstore/java/okhttp-gson-nextgen/.travis.yml new file mode 100644 index 00000000000..1b6741c083c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/README.md b/samples/client/petstore/java/okhttp-gson-nextgen/README.md new file mode 100644 index 00000000000..6110aea0fa0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/README.md @@ -0,0 +1,277 @@ +# petstore-okhttp-gson-nextgen + +OpenAPI Petstore +- API version: 1.0.0 + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + + +## Requirements + +Building the API client library requires: +1. Java 1.7+ +2. Maven (3.8.3+)/Gradle (7.2+) + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + petstore-okhttp-gson-nextgen + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy + repositories { + mavenCentral() // Needed if the 'petstore-okhttp-gson-nextgen' jar has been published to maven central. + mavenLocal() // Needed if the 'petstore-okhttp-gson-nextgen' jar has been published to the local maven repo. + } + + dependencies { + implementation "org.openapitools:petstore-okhttp-gson-nextgen:1.0.0" + } +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +* `target/petstore-okhttp-gson-nextgen-1.0.0.jar` +* `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AnotherFakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.call123testSpecialTags(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#call123testSpecialTags"); + 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 +------------ | ------------- | ------------- | ------------- +*AnotherFakeApi* | [**call123testSpecialTags**](docs/AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags +*DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooGet) | **GET** /foo | +*FakeApi* | [**fakeHealthGet**](docs/FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint +*FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | +*FakeApi* | [**fakeOuterCompositeSerialize**](docs/FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | +*FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | +*FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | +*FakeApi* | [**getArrayOfEnums**](docs/FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | +*FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | +*FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model +*FakeApi* | [**testEndpointParameters**](docs/FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**testEnumParameters**](docs/FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +*FakeApi* | [**testGroupParameters**](docs/FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeApi* | [**testInlineAdditionalProperties**](docs/FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeApi* | [**testJsonFormData**](docs/FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeApi* | [**testQueryParameterCollectionFormat**](docs/FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | +*FakeClassnameTags123Api* | [**testClassname**](docs/FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetApi* | [**uploadFileWithRequiredFile**](docs/PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [Apple](docs/Apple.md) + - [AppleReq](docs/AppleReq.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Banana](docs/Banana.md) + - [BananaReq](docs/BananaReq.md) + - [BasquePig](docs/BasquePig.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [ComplexQuadrilateral](docs/ComplexQuadrilateral.md) + - [DanishPig](docs/DanishPig.md) + - [DeprecatedObject](docs/DeprecatedObject.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [Drawing](docs/Drawing.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [EquilateralTriangle](docs/EquilateralTriangle.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [Foo](docs/Foo.md) + - [FormatTest](docs/FormatTest.md) + - [Fruit](docs/Fruit.md) + - [FruitReq](docs/FruitReq.md) + - [GmFruit](docs/GmFruit.md) + - [GrandparentAnimal](docs/GrandparentAnimal.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [HealthCheckResult](docs/HealthCheckResult.md) + - [InlineResponseDefault](docs/InlineResponseDefault.md) + - [IsoscelesTriangle](docs/IsoscelesTriangle.md) + - [Mammal](docs/Mammal.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) + - [ModelReturn](docs/ModelReturn.md) + - [Name](docs/Name.md) + - [NullableClass](docs/NullableClass.md) + - [NullableShape](docs/NullableShape.md) + - [NumberOnly](docs/NumberOnly.md) + - [ObjectWithDeprecatedFields](docs/ObjectWithDeprecatedFields.md) + - [Order](docs/Order.md) + - [OuterComposite](docs/OuterComposite.md) + - [OuterEnum](docs/OuterEnum.md) + - [OuterEnumDefaultValue](docs/OuterEnumDefaultValue.md) + - [OuterEnumInteger](docs/OuterEnumInteger.md) + - [OuterEnumIntegerDefaultValue](docs/OuterEnumIntegerDefaultValue.md) + - [ParentPet](docs/ParentPet.md) + - [Pet](docs/Pet.md) + - [Pig](docs/Pig.md) + - [Quadrilateral](docs/Quadrilateral.md) + - [QuadrilateralInterface](docs/QuadrilateralInterface.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [ScaleneTriangle](docs/ScaleneTriangle.md) + - [Shape](docs/Shape.md) + - [ShapeInterface](docs/ShapeInterface.md) + - [ShapeOrNull](docs/ShapeOrNull.md) + - [SimpleQuadrilateral](docs/SimpleQuadrilateral.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [Tag](docs/Tag.md) + - [Triangle](docs/Triangle.md) + - [TriangleInterface](docs/TriangleInterface.md) + - [User](docs/User.md) + - [Whale](docs/Whale.md) + - [Zebra](docs/Zebra.md) + + +## Documentation for Authorization + +Authentication schemes defined for the API: +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +### api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + +### bearer_test + +- **Type**: HTTP basic authentication + +### http_basic_test + +- **Type**: HTTP basic authentication + +### http_signature_test + +- **Type**: HTTP basic authentication + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/api/openapi.yaml b/samples/client/petstore/java/okhttp-gson-nextgen/api/openapi.yaml new file mode 100644 index 00000000000..8e64d05d5f2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/api/openapi.yaml @@ -0,0 +1,2464 @@ +openapi: 3.0.0 +info: + description: 'This spec is mainly for testing Petstore server and contains fake + endpoints, models. Please do not use this for any other purpose. Special characters: + " \' + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + 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 +- description: The local server without variables + url: https://127.0.0.1/no_variable +tags: +- description: Everything about your Pets + name: pet +- description: Access to Petstore orders + name: store +- description: Operations about user + name: user +paths: + /foo: + get: + responses: + default: + content: + application/json: + schema: + $ref: '#/components/schemas/inline_response_default' + description: response + x-accepts: application/json + /pet: + post: + operationId: addPet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "405": + description: Invalid input + security: + - http_signature_test: [] + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet + x-contentType: application/json + x-accepts: application/json + put: + operationId: updatePet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "400": + description: Invalid ID supplied + "404": + description: Pet not found + "405": + description: Validation exception + security: + - http_signature_test: [] + - petstore_auth: + - write:pets + - read:pets + summary: Update an existing pet + tags: + - pet + x-contentType: application/json + x-accepts: application/json + servers: + - url: http://petstore.swagger.io/v2 + - url: http://path-server-test.petstore.local/v2 + /pet/findByStatus: + get: + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - deprecated: true + description: Status values that need to be considered for filter + explode: false + in: query + name: status + required: true + schema: + items: + default: available + enum: + - available + - pending + - sold + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid status value + security: + - http_signature_test: [] + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by status + tags: + - pet + x-accepts: application/json + /pet/findByTags: + get: + deprecated: true + description: Multiple tags can be provided with comma separated strings. Use + tag1, tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - description: Tags to filter by + explode: false + in: query + name: tags + required: true + schema: + items: + type: string + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid tag value + security: + - http_signature_test: [] + - petstore_auth: + - write:pets + - read:pets + summary: Finds Pets by tags + tags: + - pet + x-accepts: application/json + /pet/{petId}: + delete: + operationId: deletePet + parameters: + - explode: false + in: header + name: api_key + required: false + schema: + type: string + style: simple + - description: Pet id to delete + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "400": + description: Invalid pet value + security: + - petstore_auth: + - write:pets + - read:pets + summary: Deletes a pet + tags: + - pet + x-accepts: application/json + get: + description: Returns a single pet + operationId: getPetById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + security: + - api_key: [] + summary: Find pet by ID + tags: + - pet + x-accepts: application/json + post: + operationId: updatePetWithForm + parameters: + - description: ID of pet that needs to be updated + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + $ref: '#/components/requestBodies/inline_object' + content: + application/x-www-form-urlencoded: + schema: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + responses: + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Updates a pet in the store with form data + tags: + - pet + x-contentType: application/x-www-form-urlencoded + x-accepts: application/json + /pet/{petId}/uploadImage: + post: + operationId: uploadFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + $ref: '#/components/requestBodies/inline_object_1' + content: + multipart/form-data: + schema: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image + tags: + - pet + x-contentType: multipart/form-data + x-accepts: application/json + /store/inventory: + get: + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + "200": + content: + application/json: + schema: + additionalProperties: + format: int32 + type: integer + type: object + description: successful operation + security: + - api_key: [] + summary: Returns pet inventories by status + tags: + - store + x-accepts: application/json + /store/order: + post: + operationId: placeOrder + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid Order + summary: Place an order for a pet + tags: + - store + x-contentType: application/json + x-accepts: application/json + /store/order/{order_id}: + delete: + description: For valid response try integer IDs with value < 1000. Anything + above 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - description: ID of the order that needs to be deleted + explode: false + in: path + name: order_id + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Delete purchase order by ID + tags: + - store + x-accepts: application/json + get: + description: For valid response try integer IDs with value <= 5 or > 10. Other + values will generated exceptions + operationId: getOrderById + parameters: + - description: ID of pet that needs to be fetched + explode: false + in: path + name: order_id + required: true + schema: + format: int64 + maximum: 5 + minimum: 1 + type: integer + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Order not found + summary: Find purchase order by ID + tags: + - store + x-accepts: application/json + /user: + post: + description: This can only be done by the logged in user. + operationId: createUser + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + responses: + default: + description: successful operation + summary: Create user + tags: + - user + x-contentType: application/json + x-accepts: application/json + /user/createWithArray: + post: + operationId: createUsersWithArrayInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-contentType: application/json + x-accepts: application/json + /user/createWithList: + post: + operationId: createUsersWithListInput + requestBody: + $ref: '#/components/requestBodies/UserArray' + responses: + default: + description: successful operation + summary: Creates list of users with given input array + tags: + - user + x-contentType: application/json + x-accepts: application/json + /user/login: + get: + operationId: loginUser + parameters: + - description: The user name for login + explode: true + in: query + name: username + required: true + schema: + type: string + style: form + - description: The password for login in clear text + explode: true + in: query + name: password + required: true + schema: + type: string + style: form + responses: + "200": + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + explode: false + schema: + format: int32 + type: integer + style: simple + X-Expires-After: + description: date in UTC when token expires + explode: false + schema: + format: date-time + type: string + style: simple + "400": + description: Invalid username/password supplied + summary: Logs user into the system + tags: + - user + x-accepts: application/json + /user/logout: + get: + operationId: logoutUser + responses: + default: + description: successful operation + summary: Logs out current logged in user session + tags: + - user + x-accepts: application/json + /user/{username}: + delete: + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - description: The name that needs to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Delete user + tags: + - user + x-accepts: application/json + get: + operationId: getUserByName + parameters: + - description: The name that needs to be fetched. Use user1 for testing. + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + description: successful operation + "400": + description: Invalid username supplied + "404": + description: User not found + summary: Get user by user name + tags: + - user + x-accepts: application/json + put: + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - description: name that need to be deleted + explode: false + in: path + name: username + required: true + schema: + type: string + style: simple + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + responses: + "400": + description: Invalid user supplied + "404": + description: User not found + summary: Updated user + tags: + - user + x-contentType: application/json + x-accepts: application/json + /fake_classname_test: + patch: + description: To test class name in snake case + operationId: testClassname + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + security: + - api_key_query: [] + summary: To test class name in snake case + tags: + - fake_classname_tags 123#$%^ + x-contentType: application/json + x-accepts: application/json + /fake: + delete: + description: Fake endpoint to test group parameters (optional) + operationId: testGroupParameters + parameters: + - description: Required String in group parameters + explode: true + in: query + name: required_string_group + required: true + schema: + type: integer + style: form + - description: Required Boolean in group parameters + explode: false + in: header + name: required_boolean_group + required: true + schema: + type: boolean + style: simple + - description: Required Integer in group parameters + explode: true + in: query + name: required_int64_group + required: true + schema: + format: int64 + type: integer + style: form + - description: String in group parameters + explode: true + in: query + name: string_group + required: false + schema: + type: integer + style: form + - description: Boolean in group parameters + explode: false + in: header + name: boolean_group + required: false + schema: + type: boolean + style: simple + - description: Integer in group parameters + explode: true + in: query + name: int64_group + required: false + schema: + format: int64 + type: integer + style: form + responses: + "400": + description: Someting wrong + security: + - bearer_test: [] + summary: Fake endpoint to test group parameters (optional) + tags: + - fake + x-group-parameters: true + x-accepts: application/json + get: + description: To test enum parameters + operationId: testEnumParameters + parameters: + - description: Header parameter enum test (string array) + explode: false + in: header + name: enum_header_string_array + required: false + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: simple + - description: Header parameter enum test (string) + explode: false + in: header + name: enum_header_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: simple + - description: Query parameter enum test (string array) + explode: true + in: query + name: enum_query_string_array + required: false + schema: + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + style: form + - description: Query parameter enum test (string) + explode: true + in: query + name: enum_query_string + required: false + schema: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_integer + required: false + schema: + enum: + - 1 + - -2 + format: int32 + type: integer + style: form + - description: Query parameter enum test (double) + explode: true + in: query + name: enum_query_double + required: false + schema: + enum: + - 1.1 + - -1.2 + format: double + type: number + style: form + requestBody: + $ref: '#/components/requestBodies/inline_object_2' + content: + application/x-www-form-urlencoded: + schema: + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + enum_form_string: + default: -efg + description: Form parameter enum test (string) + enum: + - _abc + - -efg + - (xyz) + type: string + type: object + responses: + "400": + description: Invalid request + "404": + description: Not found + summary: To test enum parameters + tags: + - fake + x-contentType: application/x-www-form-urlencoded + x-accepts: application/json + patch: + description: To test "client" model + operationId: testClientModel + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test "client" model + tags: + - fake + x-contentType: application/json + x-accepts: application/json + post: + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + requestBody: + $ref: '#/components/requestBodies/inline_object_3' + content: + application/x-www-form-urlencoded: + schema: + properties: + integer: + description: None + maximum: 100 + minimum: 10 + type: integer + int32: + description: None + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + description: None + format: int64 + type: integer + number: + description: None + maximum: 543.2 + minimum: 32.1 + type: number + float: + description: None + format: float + maximum: 987.6 + type: number + double: + description: None + format: double + maximum: 123.4 + minimum: 67.8 + type: number + string: + description: None + pattern: /[a-z]/i + type: string + pattern_without_delimiter: + description: None + pattern: ^[A-Z].* + type: string + byte: + description: None + format: byte + type: string + binary: + description: None + format: binary + type: string + date: + description: None + format: date + type: string + dateTime: + default: 2010-02-01T10:20:10.11111+01:00 + description: None + example: 2020-02-02T20:20:20.22222Z + format: date-time + type: string + password: + description: None + format: password + maxLength: 64 + minLength: 10 + type: string + callback: + description: None + type: string + required: + - byte + - double + - number + - pattern_without_delimiter + type: object + responses: + "400": + description: Invalid username supplied + "404": + description: User not found + security: + - http_basic_test: [] + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + tags: + - fake + x-contentType: application/x-www-form-urlencoded + x-accepts: application/json + /fake/outer/number: + post: + description: Test serialization of outer number types + operationId: fakeOuterNumberSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterNumber' + description: Input number as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterNumber' + description: Output number + tags: + - fake + x-contentType: application/json + x-accepts: '*/*' + /fake/outer/string: + post: + description: Test serialization of outer string types + operationId: fakeOuterStringSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterString' + description: Input string as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterString' + description: Output string + tags: + - fake + x-contentType: application/json + x-accepts: '*/*' + /fake/outer/boolean: + post: + description: Test serialization of outer boolean types + operationId: fakeOuterBooleanSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Input boolean as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Output boolean + tags: + - fake + x-contentType: application/json + x-accepts: '*/*' + /fake/outer/composite: + post: + description: Test serialization of object with outer number type + operationId: fakeOuterCompositeSerialize + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterComposite' + description: Input composite as post body + responses: + "200": + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterComposite' + description: Output composite + tags: + - fake + x-contentType: application/json + x-accepts: '*/*' + /fake/jsonFormData: + get: + operationId: testJsonFormData + requestBody: + $ref: '#/components/requestBodies/inline_object_4' + content: + application/x-www-form-urlencoded: + schema: + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + type: object + responses: + "200": + description: successful operation + summary: test json serialization of form data + tags: + - fake + x-contentType: application/x-www-form-urlencoded + x-accepts: application/json + /fake/inline-additionalProperties: + post: + operationId: testInlineAdditionalProperties + requestBody: + content: + application/json: + schema: + additionalProperties: + type: string + type: object + description: request body + required: true + responses: + "200": + description: successful operation + summary: test inline additionalProperties + tags: + - fake + x-contentType: application/json + x-accepts: application/json + /fake/body-with-query-params: + put: + operationId: testBodyWithQueryParams + parameters: + - explode: true + in: query + name: query + required: true + schema: + type: string + style: form + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + responses: + "200": + description: Success + tags: + - fake + x-contentType: application/json + x-accepts: application/json + /another-fake/dummy: + patch: + description: To test special tags and operation ID starting with number + operationId: 123_test_@#$%_special_tags + requestBody: + $ref: '#/components/requestBodies/Client' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: successful operation + summary: To test special tags + tags: + - $another-fake? + x-contentType: application/json + x-accepts: application/json + /fake/body-with-file-schema: + put: + description: For this test, the body for this request much reference a schema + named `File`. + operationId: testBodyWithFileSchema + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FileSchemaTestClass' + required: true + responses: + "200": + description: Success + tags: + - fake + x-contentType: application/json + x-accepts: application/json + /fake/test-query-parameters: + put: + description: To test the collection format in query parameters + operationId: testQueryParameterCollectionFormat + parameters: + - explode: true + in: query + name: pipe + required: true + schema: + items: + type: string + type: array + style: form + - explode: false + in: query + name: ioutil + required: true + schema: + items: + type: string + type: array + style: form + - explode: false + in: query + name: http + required: true + schema: + items: + type: string + type: array + style: spaceDelimited + - explode: false + in: query + name: url + required: true + schema: + items: + type: string + type: array + style: form + - explode: true + in: query + name: context + required: true + schema: + items: + type: string + type: array + style: form + responses: + "200": + description: Success + tags: + - fake + x-accepts: application/json + /fake/{petId}/uploadImageWithRequiredFile: + post: + operationId: uploadFileWithRequiredFile + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + $ref: '#/components/requestBodies/inline_object_5' + content: + multipart/form-data: + schema: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + format: binary + type: string + required: + - requiredFile + type: object + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads an image (required) + tags: + - pet + x-contentType: multipart/form-data + x-accepts: application/json + /fake/health: + get: + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/HealthCheckResult' + description: The instance started successfully + summary: Health check endpoint + tags: + - fake + x-accepts: application/json + /fake/array-of-enums: + get: + operationId: getArrayOfEnums + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ArrayOfEnums' + description: Got named array of enums + summary: Array of Enums + tags: + - fake + x-accepts: application/json +components: + requestBodies: + UserArray: + content: + application/json: + examples: + simple-list: + description: Should not get into code examples + summary: Simple list example + value: + - username: foo + - username: bar + schema: + items: + $ref: '#/components/schemas/User' + type: array + description: List of user object + required: true + Client: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + inline_object: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/inline_object' + inline_object_1: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/inline_object_1' + inline_object_2: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/inline_object_2' + inline_object_3: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/inline_object_3' + inline_object_4: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/inline_object_4' + inline_object_5: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/inline_object_5' + schemas: + Foo: + example: + bar: bar + properties: + bar: + default: bar + type: string + type: object + Bar: + default: bar + type: string + Order: + example: + petId: 6 + quantity: 1 + id: 0 + shipDate: 2020-02-02T20:20:20.000222Z + complete: false + status: placed + properties: + id: + format: int64 + type: integer + petId: + format: int64 + type: integer + quantity: + format: int32 + type: integer + shipDate: + example: 2020-02-02T20:20:20.000222Z + format: date-time + type: string + status: + description: Order Status + enum: + - placed + - approved + - delivered + type: string + complete: + default: false + type: boolean + type: object + xml: + name: Order + Category: + example: + name: default-name + id: 6 + properties: + id: + format: int64 + type: integer + name: + default: default-name + type: string + required: + - name + type: object + xml: + name: Category + User: + example: + firstName: firstName + lastName: lastName + password: password + userStatus: 6 + objectWithNoDeclaredPropsNullable: '{}' + phone: phone + objectWithNoDeclaredProps: '{}' + id: 0 + anyTypePropNullable: "" + email: email + anyTypeProp: "" + username: username + properties: + id: + format: int64 + type: integer + x-is-unique: true + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + description: User Status + format: int32 + type: integer + objectWithNoDeclaredProps: + description: test code generation for objects Value must be a map of strings + to values. It cannot be the 'null' value. + type: object + objectWithNoDeclaredPropsNullable: + description: test code generation for nullable objects. Value must be a + map of strings to values or the 'null' value. + nullable: true + type: object + anyTypeProp: + description: test code generation for any type Here the 'type' attribute + is not specified, which means the value can be anything, including the + null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + anyTypePropNullable: + description: test code generation for any type Here the 'type' attribute + is not specified, which means the value can be anything, including the + null value, string, number, boolean, array or object. The 'nullable' attribute + does not change the allowed values. + nullable: true + type: object + xml: + name: User + Tag: + example: + name: name + id: 1 + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + xml: + name: Tag + Pet: + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: default-name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + type: integer + x-is-unique: true + category: + $ref: '#/components/schemas/Category' + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + name: tag + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + xml: + name: Pet + ApiResponse: + example: + code: 0 + type: type + message: message + properties: + code: + format: int32 + type: integer + type: + type: string + message: + type: string + type: object + Return: + description: Model for testing reserved words + properties: + return: + format: int32 + type: integer + xml: + name: Return + Name: + description: Model for testing model name same as property name + properties: + name: + format: int32 + type: integer + snake_case: + format: int32 + readOnly: true + type: integer + property: + type: string + "123Number": + readOnly: true + type: integer + required: + - name + xml: + name: Name + "200_response": + description: Model for testing model name starting with number + properties: + name: + format: int32 + type: integer + class: + type: string + xml: + name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - $ref: '#/components/schemas/Dog_allOf' + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - $ref: '#/components/schemas/Address' + - $ref: '#/components/schemas/Cat_allOf' + Address: + additionalProperties: + type: integer + type: object + Animal: + discriminator: + propertyName: className + properties: + className: + type: string + color: + default: red + type: string + required: + - className + type: object + AnimalFarm: + items: + $ref: '#/components/schemas/Animal' + type: array + format_test: + properties: + integer: + maximum: 100 + minimum: 10 + multipleOf: 2 + type: integer + int32: + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + format: int64 + type: integer + number: + maximum: 543.2 + minimum: 32.1 + multipleOf: 32.5 + type: number + float: + format: float + maximum: 987.6 + minimum: 54.3 + type: number + double: + format: double + maximum: 123.4 + minimum: 67.8 + type: number + decimal: + format: number + type: string + string: + pattern: /[a-z]/i + type: string + byte: + format: byte + type: string + binary: + format: binary + type: string + date: + example: 2020-02-02 + format: date + type: string + dateTime: + example: 2007-12-03T10:15:30+01:00 + format: date-time + type: string + uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + type: string + password: + format: password + maxLength: 64 + minLength: 10 + type: string + pattern_with_digits: + description: A string that is a 10 digit number. Can have leading zeros. + pattern: ^\d{10}$ + type: string + pattern_with_digits_and_delimiter: + description: A string starting with 'image_' (case insensitive) and one + to three digits following i.e. Image_01. + pattern: /^image_\d{1,3}$/i + type: string + required: + - byte + - date + - number + - password + type: object + EnumClass: + default: -efg + enum: + - _abc + - -efg + - (xyz) + type: string + Enum_Test: + properties: + enum_string: + enum: + - UPPER + - lower + - "" + type: string + enum_string_required: + enum: + - UPPER + - lower + - "" + type: string + enum_integer: + enum: + - 1 + - -1 + format: int32 + type: integer + enum_integer_only: + enum: + - 2 + - -2 + type: integer + enum_number: + enum: + - 1.1 + - -1.2 + format: double + type: number + outerEnum: + $ref: '#/components/schemas/OuterEnum' + outerEnumInteger: + $ref: '#/components/schemas/OuterEnumInteger' + outerEnumDefaultValue: + $ref: '#/components/schemas/OuterEnumDefaultValue' + outerEnumIntegerDefaultValue: + $ref: '#/components/schemas/OuterEnumIntegerDefaultValue' + required: + - enum_string_required + type: object + AdditionalPropertiesClass: + properties: + map_property: + additionalProperties: + type: string + type: object + map_of_map_property: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + anytype_1: {} + map_with_undeclared_properties_anytype_1: + type: object + map_with_undeclared_properties_anytype_2: + properties: {} + type: object + map_with_undeclared_properties_anytype_3: + additionalProperties: true + type: object + empty_map: + additionalProperties: false + description: an object with no declared properties and no undeclared properties, + hence it's an empty map. + type: object + map_with_undeclared_properties_string: + additionalProperties: + type: string + type: object + type: object + MixedPropertiesAndAdditionalPropertiesClass: + properties: + uuid: + format: uuid + type: string + dateTime: + format: date-time + type: string + map: + additionalProperties: + $ref: '#/components/schemas/Animal' + type: object + type: object + List: + properties: + "123-list": + type: string + type: object + Client: + example: + client: client + properties: + client: + type: string + type: object + ReadOnlyFirst: + properties: + bar: + readOnly: true + type: string + baz: + type: string + type: object + hasOnlyReadOnly: + properties: + bar: + readOnly: true + type: string + foo: + readOnly: true + type: string + type: object + Capitalization: + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: | + Name of the pet + type: string + type: object + MapTest: + properties: + map_map_of_string: + additionalProperties: + additionalProperties: + type: string + type: object + type: object + map_of_enum_string: + additionalProperties: + enum: + - UPPER + - lower + type: string + type: object + direct_map: + additionalProperties: + type: boolean + type: object + indirect_map: + additionalProperties: + type: boolean + type: object + type: object + ArrayTest: + properties: + array_of_string: + items: + type: string + type: array + array_array_of_integer: + items: + items: + format: int64 + type: integer + type: array + type: array + array_array_of_model: + items: + items: + $ref: '#/components/schemas/ReadOnlyFirst' + type: array + type: array + type: object + NumberOnly: + properties: + JustNumber: + type: number + type: object + ArrayOfNumberOnly: + properties: + ArrayNumber: + items: + type: number + type: array + type: object + ArrayOfArrayOfNumberOnly: + properties: + ArrayArrayNumber: + items: + items: + type: number + type: array + type: array + type: object + EnumArrays: + properties: + just_symbol: + enum: + - '>=' + - $ + type: string + array_enum: + items: + enum: + - fish + - crab + type: string + type: array + type: object + OuterEnum: + enum: + - placed + - approved + - delivered + nullable: true + type: string + OuterEnumInteger: + enum: + - 0 + - 1 + - 2 + type: integer + OuterEnumDefaultValue: + default: placed + enum: + - placed + - approved + - delivered + type: string + OuterEnumIntegerDefaultValue: + default: 0 + enum: + - 0 + - 1 + - 2 + type: integer + OuterComposite: + example: + my_string: my_string + my_number: 0.8008281904610115 + my_boolean: true + properties: + my_number: + type: number + my_string: + type: string + my_boolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + type: object + OuterNumber: + type: number + OuterString: + type: string + OuterBoolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + StringBooleanMap: + additionalProperties: + type: boolean + type: object + FileSchemaTestClass: + example: + file: + sourceURI: sourceURI + files: + - sourceURI: sourceURI + - sourceURI: sourceURI + properties: + file: + $ref: '#/components/schemas/File' + files: + items: + $ref: '#/components/schemas/File' + type: array + type: object + File: + description: Must be named `File` for test. + example: + sourceURI: sourceURI + properties: + sourceURI: + description: Test capitalization + type: string + type: object + _special_model.name_: + properties: + $special[property.name]: + format: int64 + type: integer + _special_model.name_: + type: string + xml: + name: $special[model.name] + HealthCheckResult: + description: Just a string to inform instance is up and running. Make it nullable + in hope to get it as pointer in generated model. + example: + NullableMessage: NullableMessage + properties: + NullableMessage: + nullable: true + type: string + type: object + NullableClass: + additionalProperties: + nullable: true + type: object + properties: + integer_prop: + nullable: true + type: integer + number_prop: + nullable: true + type: number + boolean_prop: + nullable: true + type: boolean + string_prop: + nullable: true + type: string + date_prop: + format: date + nullable: true + type: string + datetime_prop: + format: date-time + nullable: true + type: string + array_nullable_prop: + items: + type: object + nullable: true + type: array + array_and_items_nullable_prop: + items: + nullable: true + type: object + nullable: true + type: array + array_items_nullable: + items: + nullable: true + type: object + type: array + object_nullable_prop: + additionalProperties: + type: object + nullable: true + type: object + object_and_items_nullable_prop: + additionalProperties: + nullable: true + type: object + nullable: true + type: object + object_items_nullable: + additionalProperties: + nullable: true + type: object + type: object + type: object + fruit: + additionalProperties: false + oneOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + properties: + color: + type: string + apple: + nullable: true + properties: + cultivar: + pattern: ^[a-zA-Z\s]*$ + type: string + origin: + pattern: /^[A-Z\s]*$/i + type: string + type: object + banana: + properties: + lengthCm: + type: number + type: object + mammal: + discriminator: + propertyName: className + oneOf: + - $ref: '#/components/schemas/whale' + - $ref: '#/components/schemas/zebra' + - $ref: '#/components/schemas/Pig' + whale: + properties: + hasBaleen: + type: boolean + hasTeeth: + type: boolean + className: + type: string + required: + - className + type: object + zebra: + additionalProperties: true + properties: + type: + enum: + - plains + - mountain + - grevys + type: string + className: + type: string + required: + - className + type: object + Pig: + discriminator: + propertyName: className + oneOf: + - $ref: '#/components/schemas/BasquePig' + - $ref: '#/components/schemas/DanishPig' + BasquePig: + properties: + className: + type: string + required: + - className + type: object + DanishPig: + properties: + className: + type: string + required: + - className + type: object + gmFruit: + additionalProperties: false + anyOf: + - $ref: '#/components/schemas/apple' + - $ref: '#/components/schemas/banana' + properties: + color: + type: string + fruitReq: + additionalProperties: false + oneOf: + - type: "null" + - $ref: '#/components/schemas/appleReq' + - $ref: '#/components/schemas/bananaReq' + appleReq: + additionalProperties: false + properties: + cultivar: + type: string + mealy: + type: boolean + required: + - cultivar + type: object + bananaReq: + additionalProperties: false + properties: + lengthCm: + type: number + sweet: + type: boolean + required: + - lengthCm + type: object + Drawing: + additionalProperties: + $ref: '#/components/schemas/fruit' + properties: + mainShape: + $ref: '#/components/schemas/Shape' + shapeOrNull: + $ref: '#/components/schemas/ShapeOrNull' + nullableShape: + $ref: '#/components/schemas/NullableShape' + shapes: + items: + $ref: '#/components/schemas/Shape' + type: array + type: object + Shape: + discriminator: + propertyName: shapeType + oneOf: + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + ShapeOrNull: + description: The value may be a shape or the 'null' value. This is introduced + in OAS schema >= 3.1. + discriminator: + propertyName: shapeType + oneOf: + - type: "null" + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + NullableShape: + description: The value may be a shape or the 'null' value. The 'nullable' attribute + was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema + >= 3.1. + discriminator: + propertyName: shapeType + nullable: true + oneOf: + - $ref: '#/components/schemas/Triangle' + - $ref: '#/components/schemas/Quadrilateral' + ShapeInterface: + properties: + shapeType: + type: string + required: + - shapeType + TriangleInterface: + properties: + triangleType: + type: string + required: + - triangleType + Triangle: + discriminator: + propertyName: triangleType + oneOf: + - $ref: '#/components/schemas/EquilateralTriangle' + - $ref: '#/components/schemas/IsoscelesTriangle' + - $ref: '#/components/schemas/ScaleneTriangle' + EquilateralTriangle: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/TriangleInterface' + IsoscelesTriangle: + additionalProperties: false + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/TriangleInterface' + ScaleneTriangle: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/TriangleInterface' + QuadrilateralInterface: + properties: + quadrilateralType: + type: string + required: + - quadrilateralType + Quadrilateral: + discriminator: + propertyName: quadrilateralType + oneOf: + - $ref: '#/components/schemas/SimpleQuadrilateral' + - $ref: '#/components/schemas/ComplexQuadrilateral' + SimpleQuadrilateral: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/QuadrilateralInterface' + ComplexQuadrilateral: + allOf: + - $ref: '#/components/schemas/ShapeInterface' + - $ref: '#/components/schemas/QuadrilateralInterface' + GrandparentAnimal: + discriminator: + propertyName: pet_type + properties: + pet_type: + type: string + required: + - pet_type + type: object + ParentPet: + allOf: + - $ref: '#/components/schemas/GrandparentAnimal' + type: object + ArrayOfEnums: + items: + $ref: '#/components/schemas/OuterEnum' + type: array + DateTimeTest: + default: 2010-01-01T10:10:10.000111+01:00 + example: 2010-01-01T10:10:10.000111+01:00 + format: date-time + type: string + DeprecatedObject: + deprecated: true + properties: + name: + type: string + type: object + ObjectWithDeprecatedFields: + properties: + uuid: + type: string + id: + deprecated: true + type: number + deprecatedRef: + $ref: '#/components/schemas/DeprecatedObject' + bars: + deprecated: true + items: + $ref: '#/components/schemas/Bar' + type: array + type: object + inline_response_default: + example: + string: + bar: bar + properties: + string: + $ref: '#/components/schemas/Foo' + type: object + inline_object: + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + type: object + inline_object_1: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + format: binary + type: string + type: object + inline_object_2: + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + items: + default: $ + enum: + - '>' + - $ + type: string + type: array + enum_form_string: + default: -efg + description: Form parameter enum test (string) + enum: + - _abc + - -efg + - (xyz) + type: string + type: object + inline_object_3: + properties: + integer: + description: None + maximum: 100 + minimum: 10 + type: integer + int32: + description: None + format: int32 + maximum: 200 + minimum: 20 + type: integer + int64: + description: None + format: int64 + type: integer + number: + description: None + maximum: 543.2 + minimum: 32.1 + type: number + float: + description: None + format: float + maximum: 987.6 + type: number + double: + description: None + format: double + maximum: 123.4 + minimum: 67.8 + type: number + string: + description: None + pattern: /[a-z]/i + type: string + pattern_without_delimiter: + description: None + pattern: ^[A-Z].* + type: string + byte: + description: None + format: byte + type: string + binary: + description: None + format: binary + type: string + date: + description: None + format: date + type: string + dateTime: + default: 2010-02-01T10:20:10.11111+01:00 + description: None + example: 2020-02-02T20:20:20.22222Z + format: date-time + type: string + password: + description: None + format: password + maxLength: 64 + minLength: 10 + type: string + callback: + description: None + type: string + required: + - byte + - double + - number + - pattern_without_delimiter + type: object + inline_object_4: + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + type: object + inline_object_5: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + format: binary + type: string + required: + - requiredFile + type: object + Dog_allOf: + properties: + breed: + type: string + type: object + Cat_allOf: + properties: + declawed: + type: boolean + type: object + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 + api_key: + in: header + name: api_key + type: apiKey + api_key_query: + in: query + name: api_key_query + type: apiKey + http_basic_test: + scheme: basic + type: http + bearer_test: + bearerFormat: JWT + scheme: bearer + type: http + http_signature_test: + scheme: signature + type: http + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/build.gradle b/samples/client/petstore/java/okhttp-gson-nextgen/build.gradle new file mode 100644 index 00000000000..e73647ffcb6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/build.gradle @@ -0,0 +1,153 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' +apply plugin: 'java' +apply plugin: 'com.diffplug.spotless' + +group = 'org.openapitools' +version = '1.0.0' + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.5' + classpath 'com.diffplug.spotless:spotless-plugin-gradle:5.17.1' + } +} + +repositories { + mavenCentral() +} +sourceSets { + main.java.srcDirs = ['src/main/java'] +} + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 25 + buildToolsVersion '25.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 25 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + } + } + + 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-publish' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + publishing { + publications { + maven(MavenPublication) { + artifactId = 'petstore-okhttp-gson-nextgen' + from components.java + } + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + jakarta_annotation_version = "1.3.5" +} + +dependencies { + implementation 'io.swagger:swagger-annotations:1.5.24' + implementation "com.google.code.findbugs:jsr305:3.0.2" + implementation 'com.squareup.okhttp3:okhttp:4.9.1' + implementation 'com.squareup.okhttp3:logging-interceptor:4.9.1' + implementation 'com.google.code.gson:gson:2.8.6' + implementation 'io.gsonfire:gson-fire:1.8.4' + implementation 'org.openapitools:jackson-databind-nullable:0.2.1' + implementation group: 'org.apache.oltu.oauth2', name: 'org.apache.oltu.oauth2.client', version: '1.0.1' + implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.10' + implementation 'org.threeten:threetenbp:1.4.3' + implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + testImplementation 'junit:junit:4.13.1' + testImplementation 'org.mockito:mockito-core:3.11.2' +} + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} + +// Use spotless plugin to automatically format code, remove unused import, etc +// To apply changes directly to the file, run `gradlew spotlessApply` +// Ref: https://github.com/diffplug/spotless/tree/main/plugin-gradle +spotless { + // comment out below to run spotless as part of the `check` task + enforceCheck false + + format 'misc', { + // define the files (e.g. '*.gradle', '*.md') to apply `misc` to + target '.gitignore' + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithSpaces() // Takes an integer argument if you don't like 4 + endWithNewline() + } + java { + // don't need to set target, it is inferred from java + + // apply a specific flavor of google-java-format + googleJavaFormat('1.8').aosp().reflowLongStrings() + + removeUnusedImports() + importOrder() + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/build.sbt b/samples/client/petstore/java/okhttp-gson-nextgen/build.sbt new file mode 100644 index 00000000000..6aebfa8e21c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/build.sbt @@ -0,0 +1,27 @@ +lazy val root = (project in file(".")). + settings( + organization := "org.openapitools", + name := "petstore-okhttp-gson-nextgen", + 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.24", + "com.squareup.okhttp3" % "okhttp" % "4.9.1", + "com.squareup.okhttp3" % "logging-interceptor" % "4.9.1", + "com.google.code.gson" % "gson" % "2.8.6", + "org.apache.commons" % "commons-lang3" % "3.10", + "org.openapitools" % "jackson-databind-nullable" % "0.2.1", + "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1", + "org.threeten" % "threetenbp" % "1.4.3" % "compile", + "io.gsonfire" % "gson-fire" % "1.8.3" % "compile", + "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", + "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", + "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", + "junit" % "junit" % "4.13.1" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesAnyType.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesAnyType.md new file mode 100644 index 00000000000..7bbe63d23f8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesAnyType.md @@ -0,0 +1,13 @@ + + +# AdditionalPropertiesAnyType + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesArray.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesArray.md new file mode 100644 index 00000000000..bdbf2962f20 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesArray.md @@ -0,0 +1,13 @@ + + +# AdditionalPropertiesArray + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesBoolean.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesBoolean.md new file mode 100644 index 00000000000..81aeb9ae1e7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesBoolean.md @@ -0,0 +1,13 @@ + + +# AdditionalPropertiesBoolean + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..3d032d4504a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesClass.md @@ -0,0 +1,20 @@ + + +# AdditionalPropertiesClass + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapProperty** | **Map<String, String>** | | [optional] +**mapOfMapProperty** | **Map<String, Map<String, String>>** | | [optional] +**anytype1** | **Object** | | [optional] +**mapWithUndeclaredPropertiesAnytype1** | **Object** | | [optional] +**mapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] +**mapWithUndeclaredPropertiesAnytype3** | **Map<String, Object>** | | [optional] +**emptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] +**mapWithUndeclaredPropertiesString** | **Map<String, String>** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesInteger.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesInteger.md new file mode 100644 index 00000000000..ae339123714 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesInteger.md @@ -0,0 +1,13 @@ + + +# AdditionalPropertiesInteger + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesNumber.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesNumber.md new file mode 100644 index 00000000000..8f414ad02fd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesNumber.md @@ -0,0 +1,13 @@ + + +# AdditionalPropertiesNumber + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesObject.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesObject.md new file mode 100644 index 00000000000..41892793f0b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesObject.md @@ -0,0 +1,13 @@ + + +# AdditionalPropertiesObject + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesString.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesString.md new file mode 100644 index 00000000000..a2dfbc116f9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AdditionalPropertiesString.md @@ -0,0 +1,13 @@ + + +# AdditionalPropertiesString + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Animal.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Animal.md new file mode 100644 index 00000000000..7edc25cd2b0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Animal.md @@ -0,0 +1,14 @@ + + +# Animal + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AnimalFarm.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AnimalFarm.md new file mode 100644 index 00000000000..c7c7f1ddcce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AnimalFarm.md @@ -0,0 +1,9 @@ + +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AnotherFakeApi.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AnotherFakeApi.md new file mode 100644 index 00000000000..149488eff9a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AnotherFakeApi.md @@ -0,0 +1,71 @@ +# AnotherFakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call123testSpecialTags**](AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags + + + +# **call123testSpecialTags** +> Client call123testSpecialTags(client) + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AnotherFakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.call123testSpecialTags(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#call123testSpecialTags"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Apple.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Apple.md new file mode 100644 index 00000000000..513643aeb77 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Apple.md @@ -0,0 +1,14 @@ + + +# Apple + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**cultivar** | **String** | | [optional] +**origin** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/AppleReq.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AppleReq.md new file mode 100644 index 00000000000..d2fccd5306d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/AppleReq.md @@ -0,0 +1,14 @@ + + +# AppleReq + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**cultivar** | **String** | | +**mealy** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..9b1f8586999 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,13 @@ + + +# ArrayOfArrayOfNumberOnly + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | **List<List<BigDecimal>>** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayOfNumberOnly.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..4e95f1ae74e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayOfNumberOnly.md @@ -0,0 +1,13 @@ + + +# ArrayOfNumberOnly + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | **List<BigDecimal>** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayTest.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayTest.md new file mode 100644 index 00000000000..9b90810fc28 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ArrayTest.md @@ -0,0 +1,15 @@ + + +# ArrayTest + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **List<String>** | | [optional] +**arrayArrayOfInteger** | **List<List<Long>>** | | [optional] +**arrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Banana.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Banana.md new file mode 100644 index 00000000000..7ddff9847aa --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Banana.md @@ -0,0 +1,13 @@ + + +# Banana + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**lengthCm** | **BigDecimal** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/BananaReq.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/BananaReq.md new file mode 100644 index 00000000000..35a773503b8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/BananaReq.md @@ -0,0 +1,14 @@ + + +# BananaReq + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**lengthCm** | **BigDecimal** | | +**sweet** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/BasquePig.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/BasquePig.md new file mode 100644 index 00000000000..05d4cf39707 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/BasquePig.md @@ -0,0 +1,13 @@ + + +# BasquePig + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/BigCat.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/BigCat.md new file mode 100644 index 00000000000..020fbc787d8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/BigCat.md @@ -0,0 +1,24 @@ + + +# BigCat + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | [**KindEnum**](#KindEnum) | | [optional] + + + +## Enum: KindEnum + +Name | Value +---- | ----- +LIONS | "lions" +TIGERS | "tigers" +LEOPARDS | "leopards" +JAGUARS | "jaguars" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/BigCatAllOf.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/BigCatAllOf.md new file mode 100644 index 00000000000..2bcace910ec --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/BigCatAllOf.md @@ -0,0 +1,24 @@ + + +# BigCatAllOf + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**kind** | [**KindEnum**](#KindEnum) | | [optional] + + + +## Enum: KindEnum + +Name | Value +---- | ----- +LIONS | "lions" +TIGERS | "tigers" +LEOPARDS | "leopards" +JAGUARS | "jaguars" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Capitalization.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Capitalization.md new file mode 100644 index 00000000000..ad8939b744c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Capitalization.md @@ -0,0 +1,18 @@ + + +# Capitalization + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**scAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Cat.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Cat.md new file mode 100644 index 00000000000..87a3ab44a39 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Cat.md @@ -0,0 +1,13 @@ + + +# Cat + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/CatAllOf.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/CatAllOf.md new file mode 100644 index 00000000000..3fd01aaebfc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/CatAllOf.md @@ -0,0 +1,13 @@ + + +# CatAllOf + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Category.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Category.md new file mode 100644 index 00000000000..d03ffbfd06f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Category.md @@ -0,0 +1,14 @@ + + +# Category + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ChildCat.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ChildCat.md new file mode 100644 index 00000000000..ca161f80372 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ChildCat.md @@ -0,0 +1,22 @@ + + +# ChildCat + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] +**petType** | [**PetTypeEnum**](#PetTypeEnum) | | + + + +## Enum: PetTypeEnum + +Name | Value +---- | ----- +CHILDCAT | "ChildCat" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ChildCatAllOf.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ChildCatAllOf.md new file mode 100644 index 00000000000..e7ace5e06bf --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ChildCatAllOf.md @@ -0,0 +1,22 @@ + + +# ChildCatAllOf + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] +**petType** | [**PetTypeEnum**](#PetTypeEnum) | | [optional] + + + +## Enum: PetTypeEnum + +Name | Value +---- | ----- +CHILDCAT | "ChildCat" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ClassModel.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ClassModel.md new file mode 100644 index 00000000000..04beba3384a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ClassModel.md @@ -0,0 +1,14 @@ + + +# ClassModel + +Model for testing model with \"_class\" property + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Client.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Client.md new file mode 100644 index 00000000000..125a20b3fce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Client.md @@ -0,0 +1,13 @@ + + +# Client + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ComplexQuadrilateral.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ComplexQuadrilateral.md new file mode 100644 index 00000000000..9e7a27f8a59 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ComplexQuadrilateral.md @@ -0,0 +1,14 @@ + + +# ComplexQuadrilateral + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**quadrilateralType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/DanishPig.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/DanishPig.md new file mode 100644 index 00000000000..0e86a671658 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/DanishPig.md @@ -0,0 +1,13 @@ + + +# DanishPig + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/DefaultApi.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/DefaultApi.md new file mode 100644 index 00000000000..311c4fa6bbc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/DefaultApi.md @@ -0,0 +1,65 @@ +# DefaultApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fooGet**](DefaultApi.md#fooGet) | **GET** /foo | + + + +# **fooGet** +> InlineResponseDefault fooGet() + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + try { + InlineResponseDefault result = apiInstance.fooGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#fooGet"); + 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 + +[**InlineResponseDefault**](InlineResponseDefault.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**0** | response | - | + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/DeprecatedObject.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/DeprecatedObject.md new file mode 100644 index 00000000000..d5128bdb84a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/DeprecatedObject.md @@ -0,0 +1,13 @@ + + +# DeprecatedObject + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Dog.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Dog.md new file mode 100644 index 00000000000..f4ba57fa3b8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Dog.md @@ -0,0 +1,13 @@ + + +# Dog + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/DogAllOf.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/DogAllOf.md new file mode 100644 index 00000000000..1f7e23d981b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/DogAllOf.md @@ -0,0 +1,13 @@ + + +# DogAllOf + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Drawing.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Drawing.md new file mode 100644 index 00000000000..0874f4811de --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Drawing.md @@ -0,0 +1,16 @@ + + +# Drawing + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mainShape** | [**Shape**](Shape.md) | | [optional] +**shapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] +**nullableShape** | [**NullableShape**](NullableShape.md) | | [optional] +**shapes** | [**List<Shape>**](Shape.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumArrays.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumArrays.md new file mode 100644 index 00000000000..94505276726 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumArrays.md @@ -0,0 +1,32 @@ + + +# EnumArrays + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | [**JustSymbolEnum**](#JustSymbolEnum) | | [optional] +**arrayEnum** | [**List<ArrayEnumEnum>**](#List<ArrayEnumEnum>) | | [optional] + + + +## Enum: JustSymbolEnum + +Name | Value +---- | ----- +GREATER_THAN_OR_EQUAL_TO | ">=" +DOLLAR | "$" + + + +## Enum: List<ArrayEnumEnum> + +Name | Value +---- | ----- +FISH | "fish" +CRAB | "crab" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumClass.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumClass.md new file mode 100644 index 00000000000..b314590a759 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumClass.md @@ -0,0 +1,15 @@ + + +# EnumClass + +## Enum + + +* `_ABC` (value: `"_abc"`) + +* `_EFG` (value: `"-efg"`) + +* `_XYZ_` (value: `"(xyz)"`) + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumTest.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumTest.md new file mode 100644 index 00000000000..342b462ccc0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/EnumTest.md @@ -0,0 +1,68 @@ + + +# EnumTest + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | [**EnumStringEnum**](#EnumStringEnum) | | [optional] +**enumStringRequired** | [**EnumStringRequiredEnum**](#EnumStringRequiredEnum) | | +**enumInteger** | [**EnumIntegerEnum**](#EnumIntegerEnum) | | [optional] +**enumIntegerOnly** | [**EnumIntegerOnlyEnum**](#EnumIntegerOnlyEnum) | | [optional] +**enumNumber** | [**EnumNumberEnum**](#EnumNumberEnum) | | [optional] +**outerEnum** | **OuterEnum** | | [optional] +**outerEnumInteger** | **OuterEnumInteger** | | [optional] +**outerEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**outerEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] + + + +## Enum: EnumStringEnum + +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" +EMPTY | "" + + + +## Enum: EnumStringRequiredEnum + +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" +EMPTY | "" + + + +## Enum: EnumIntegerEnum + +Name | Value +---- | ----- +NUMBER_1 | 1 +NUMBER_MINUS_1 | -1 + + + +## Enum: EnumIntegerOnlyEnum + +Name | Value +---- | ----- +NUMBER_2 | 2 +NUMBER_MINUS_2 | -2 + + + +## Enum: EnumNumberEnum + +Name | Value +---- | ----- +NUMBER_1_DOT_1 | 1.1 +NUMBER_MINUS_1_DOT_2 | -1.2 + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/EquilateralTriangle.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/EquilateralTriangle.md new file mode 100644 index 00000000000..e4b49735d65 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/EquilateralTriangle.md @@ -0,0 +1,14 @@ + + +# EquilateralTriangle + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**triangleType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FakeApi.md new file mode 100644 index 00000000000..3401bb6eeb0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FakeApi.md @@ -0,0 +1,1006 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fakeHealthGet**](FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint +[**fakeOuterBooleanSerialize**](FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeApi.md#fakeOuterCompositeSerialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | +[**getArrayOfEnums**](FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums +[**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | +[**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | +[**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeApi.md#testEndpointParameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeApi.md#testEnumParameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeApi.md#testGroupParameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeApi.md#testInlineAdditionalProperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeApi.md#testJsonFormData) | **GET** /fake/jsonFormData | test json serialization of form data +[**testQueryParameterCollectionFormat**](FakeApi.md#testQueryParameterCollectionFormat) | **PUT** /fake/test-query-parameters | + + + +# **fakeHealthGet** +> HealthCheckResult fakeHealthGet() + +Health check endpoint + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + HealthCheckResult result = apiInstance.fakeHealthGet(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeHealthGet"); + 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 + +[**HealthCheckResult**](HealthCheckResult.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | The instance started successfully | - | + + +# **fakeOuterBooleanSerialize** +> Boolean fakeOuterBooleanSerialize(body) + + + +Test serialization of outer boolean types + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Boolean body = true; // Boolean | Input boolean as post body + try { + Boolean result = apiInstance.fakeOuterBooleanSerialize(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterBooleanSerialize"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Boolean**| Input boolean as post body | [optional] + +### Return type + +**Boolean** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output boolean | - | + + +# **fakeOuterCompositeSerialize** +> OuterComposite fakeOuterCompositeSerialize(outerComposite) + + + +Test serialization of object with outer number type + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + OuterComposite outerComposite = new OuterComposite(); // OuterComposite | Input composite as post body + try { + OuterComposite result = apiInstance.fakeOuterCompositeSerialize(outerComposite); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterCompositeSerialize"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **outerComposite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output composite | - | + + +# **fakeOuterNumberSerialize** +> BigDecimal fakeOuterNumberSerialize(body) + + + +Test serialization of outer number types + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + BigDecimal body = new BigDecimal(78); // BigDecimal | Input number as post body + try { + BigDecimal result = apiInstance.fakeOuterNumberSerialize(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterNumberSerialize"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **BigDecimal**| Input number as post body | [optional] + +### Return type + +[**BigDecimal**](BigDecimal.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output number | - | + + +# **fakeOuterStringSerialize** +> String fakeOuterStringSerialize(body) + + + +Test serialization of outer string types + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + String body = "body_example"; // String | Input string as post body + try { + String result = apiInstance.fakeOuterStringSerialize(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#fakeOuterStringSerialize"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String**| Input string as post body | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: */* + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Output string | - | + + +# **getArrayOfEnums** +> List<OuterEnum> getArrayOfEnums() + +Array of Enums + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + List result = apiInstance.getArrayOfEnums(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#getArrayOfEnums"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**List<OuterEnum>**](OuterEnum.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Got named array of enums | - | + + +# **testBodyWithFileSchema** +> testBodyWithFileSchema(fileSchemaTestClass) + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + FileSchemaTestClass fileSchemaTestClass = new FileSchemaTestClass(); // FileSchemaTestClass | + try { + apiInstance.testBodyWithFileSchema(fileSchemaTestClass); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testBodyWithFileSchema"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **fileSchemaTestClass** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + + +# **testBodyWithQueryParams** +> testBodyWithQueryParams(query, user) + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + String query = "query_example"; // String | + User user = new User(); // User | + try { + apiInstance.testBodyWithQueryParams(query, user); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testBodyWithQueryParams"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **String**| | + **user** | [**User**](User.md)| | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + + +# **testClientModel** +> Client testClientModel(client) + +To test \"client\" model + +To test \"client\" model + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.testClientModel(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testClientModel"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + + +# **testEndpointParameters** +> testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback) + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### 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.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure HTTP basic authorization: http_basic_test + HttpBasicAuth http_basic_test = (HttpBasicAuth) defaultClient.getAuthentication("http_basic_test"); + http_basic_test.setUsername("YOUR USERNAME"); + http_basic_test.setPassword("YOUR PASSWORD"); + + FakeApi apiInstance = new FakeApi(defaultClient); + BigDecimal number = new BigDecimal(78); // BigDecimal | None + Double _double = 3.4D; // Double | None + String patternWithoutDelimiter = "patternWithoutDelimiter_example"; // String | None + byte[] _byte = null; // byte[] | None + Integer integer = 56; // Integer | None + Integer int32 = 56; // Integer | None + Long int64 = 56L; // Long | None + Float _float = 3.4F; // Float | None + String string = "string_example"; // String | None + File binary = new File("/path/to/file"); // File | None + LocalDate date = LocalDate.now(); // LocalDate | None + OffsetDateTime dateTime = OffsetDateTime.parse("OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))"); // OffsetDateTime | None + String password = "password_example"; // String | None + String paramCallback = "paramCallback_example"; // String | None + try { + apiInstance.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEndpointParameters"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **number** | **BigDecimal**| None | + **_double** | **Double**| None | + **patternWithoutDelimiter** | **String**| None | + **_byte** | **byte[]**| None | + **integer** | **Integer**| None | [optional] + **int32** | **Integer**| None | [optional] + **int64** | **Long**| None | [optional] + **_float** | **Float**| None | [optional] + **string** | **String**| None | [optional] + **binary** | **File**| None | [optional] + **date** | **LocalDate**| None | [optional] + **dateTime** | **OffsetDateTime**| None | [optional] [default to OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))] + **password** | **String**| None | [optional] + **paramCallback** | **String**| None | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid username supplied | - | +**404** | User not found | - | + + +# **testEnumParameters** +> testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString) + +To test enum parameters + +To test enum parameters + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + List enumHeaderStringArray = Arrays.asList("$"); // List | Header parameter enum test (string array) + String enumHeaderString = "_abc"; // String | Header parameter enum test (string) + List enumQueryStringArray = Arrays.asList("$"); // List | Query parameter enum test (string array) + String enumQueryString = "_abc"; // String | Query parameter enum test (string) + Integer enumQueryInteger = 1; // Integer | Query parameter enum test (double) + Double enumQueryDouble = 1.1D; // Double | Query parameter enum test (double) + List enumFormStringArray = Arrays.asList("$"); // List | Form parameter enum test (string array) + String enumFormString = "_abc"; // String | Form parameter enum test (string) + try { + apiInstance.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testEnumParameters"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumHeaderStringArray** | [**List<String>**](String.md)| Header parameter enum test (string array) | [optional] [enum: >, $] + **enumHeaderString** | **String**| Header parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryStringArray** | [**List<String>**](String.md)| Query parameter enum test (string array) | [optional] [enum: >, $] + **enumQueryString** | **String**| Query parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + **enumQueryInteger** | **Integer**| Query parameter enum test (double) | [optional] [enum: 1, -2] + **enumQueryDouble** | **Double**| Query parameter enum test (double) | [optional] [enum: 1.1, -1.2] + **enumFormStringArray** | [**List<String>**](String.md)| Form parameter enum test (string array) | [optional] [enum: >, $] + **enumFormString** | **String**| Form parameter enum test (string) | [optional] [default to -efg] [enum: _abc, -efg, (xyz)] + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid request | - | +**404** | Not found | - | + + +# **testGroupParameters** +> testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group).stringGroup(stringGroup).booleanGroup(booleanGroup).int64Group(int64Group).execute(); + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### 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.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure HTTP bearer authorization: bearer_test + HttpBearerAuth bearer_test = (HttpBearerAuth) defaultClient.getAuthentication("bearer_test"); + bearer_test.setBearerToken("BEARER TOKEN"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Integer requiredStringGroup = 56; // Integer | Required String in group parameters + Boolean requiredBooleanGroup = true; // Boolean | Required Boolean in group parameters + Long requiredInt64Group = 56L; // Long | Required Integer in group parameters + Integer stringGroup = 56; // Integer | String in group parameters + Boolean booleanGroup = true; // Boolean | Boolean in group parameters + Long int64Group = 56L; // Long | Integer in group parameters + try { + apiInstance.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group) + .stringGroup(stringGroup) + .booleanGroup(booleanGroup) + .int64Group(int64Group) + .execute(); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testGroupParameters"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requiredStringGroup** | **Integer**| Required String in group parameters | + **requiredBooleanGroup** | **Boolean**| Required Boolean in group parameters | + **requiredInt64Group** | **Long**| Required Integer in group parameters | + **stringGroup** | **Integer**| String in group parameters | [optional] + **booleanGroup** | **Boolean**| Boolean in group parameters | [optional] + **int64Group** | **Long**| Integer in group parameters | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[bearer_test](../README.md#bearer_test) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Someting wrong | - | + + +# **testInlineAdditionalProperties** +> testInlineAdditionalProperties(requestBody) + +test inline additionalProperties + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = new HashMap(); // Map | request body + try { + apiInstance.testInlineAdditionalProperties(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testInlineAdditionalProperties"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**Map<String, String>**](String.md)| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + + +# **testJsonFormData** +> testJsonFormData(param, param2) + +test json serialization of form data + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + String param = "param_example"; // String | field1 + String param2 = "param2_example"; // String | field2 + try { + apiInstance.testJsonFormData(param, param2); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testJsonFormData"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **String**| field1 | + **param2** | **String**| field2 | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + + +# **testQueryParameterCollectionFormat** +> testQueryParameterCollectionFormat(pipe, ioutil, http, url, context) + + + +To test the collection format in query parameters + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + List pipe = Arrays.asList(); // List | + List ioutil = Arrays.asList(); // List | + List http = Arrays.asList(); // List | + List url = Arrays.asList(); // List | + List context = Arrays.asList(); // List | + try { + apiInstance.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testQueryParameterCollectionFormat"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pipe** | [**List<String>**](String.md)| | + **ioutil** | [**List<String>**](String.md)| | + **http** | [**List<String>**](String.md)| | + **url** | [**List<String>**](String.md)| | + **context** | [**List<String>**](String.md)| | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Success | - | + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/FakeClassnameTags123Api.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FakeClassnameTags123Api.md new file mode 100644 index 00000000000..dbd12c37f05 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FakeClassnameTags123Api.md @@ -0,0 +1,78 @@ +# FakeClassnameTags123Api + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClassname**](FakeClassnameTags123Api.md#testClassname) | **PATCH** /fake_classname_test | To test class name in snake case + + + +# **testClassname** +> Client testClassname(client) + +To test class name in snake case + +To test class name in snake case + +### 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.models.*; +import org.openapitools.client.api.FakeClassnameTags123Api; + +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"); + + FakeClassnameTags123Api apiInstance = new FakeClassnameTags123Api(defaultClient); + Client client = new Client(); // Client | client model + try { + Client result = apiInstance.testClassname(client); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeClassnameTags123Api#testClassname"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **client** | [**Client**](Client.md)| client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/FileSchemaTestClass.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FileSchemaTestClass.md new file mode 100644 index 00000000000..2602dc74610 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FileSchemaTestClass.md @@ -0,0 +1,14 @@ + + +# FileSchemaTestClass + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**file** | [**java.io.File**](java.io.File.md) | | [optional] +**files** | [**List<java.io.File>**](java.io.File.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Foo.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Foo.md new file mode 100644 index 00000000000..7893cf3f447 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Foo.md @@ -0,0 +1,13 @@ + + +# Foo + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/FormatTest.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FormatTest.md new file mode 100644 index 00000000000..91da637f088 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FormatTest.md @@ -0,0 +1,28 @@ + + +# FormatTest + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Integer** | | [optional] +**int32** | **Integer** | | [optional] +**int64** | **Long** | | [optional] +**number** | **BigDecimal** | | +**_float** | **Float** | | [optional] +**_double** | **Double** | | [optional] +**decimal** | **BigDecimal** | | [optional] +**string** | **String** | | [optional] +**_byte** | **byte[]** | | +**binary** | **File** | | [optional] +**date** | **LocalDate** | | +**dateTime** | **OffsetDateTime** | | [optional] +**uuid** | **UUID** | | [optional] +**password** | **String** | | +**patternWithDigits** | **String** | A string that is a 10 digit number. Can have leading zeros. | [optional] +**patternWithDigitsAndDelimiter** | **String** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Fruit.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Fruit.md new file mode 100644 index 00000000000..75fcaa52b2c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Fruit.md @@ -0,0 +1,16 @@ + + +# Fruit + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**color** | **String** | | [optional] +**cultivar** | **String** | | [optional] +**origin** | **String** | | [optional] +**lengthCm** | **BigDecimal** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/FruitReq.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FruitReq.md new file mode 100644 index 00000000000..2f45fd6d70e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/FruitReq.md @@ -0,0 +1,16 @@ + + +# FruitReq + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**cultivar** | **String** | | +**mealy** | **Boolean** | | [optional] +**lengthCm** | **BigDecimal** | | +**sweet** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/GmFruit.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/GmFruit.md new file mode 100644 index 00000000000..1536d689689 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/GmFruit.md @@ -0,0 +1,16 @@ + + +# GmFruit + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**color** | **String** | | [optional] +**cultivar** | **String** | | [optional] +**origin** | **String** | | [optional] +**lengthCm** | **BigDecimal** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/GrandparentAnimal.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/GrandparentAnimal.md new file mode 100644 index 00000000000..8c7632266ed --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/GrandparentAnimal.md @@ -0,0 +1,13 @@ + + +# GrandparentAnimal + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**petType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/HasOnlyReadOnly.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..6416f8f3715 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/HasOnlyReadOnly.md @@ -0,0 +1,14 @@ + + +# HasOnlyReadOnly + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**foo** | **String** | | [optional] [readonly] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/HealthCheckResult.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/HealthCheckResult.md new file mode 100644 index 00000000000..80ba4783bbd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/HealthCheckResult.md @@ -0,0 +1,14 @@ + + +# HealthCheckResult + +Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**nullableMessage** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/InlineResponseDefault.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/InlineResponseDefault.md new file mode 100644 index 00000000000..1c7c639d48c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/InlineResponseDefault.md @@ -0,0 +1,13 @@ + + +# InlineResponseDefault + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**string** | [**Foo**](Foo.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/IsoscelesTriangle.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/IsoscelesTriangle.md new file mode 100644 index 00000000000..535e9216413 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/IsoscelesTriangle.md @@ -0,0 +1,14 @@ + + +# IsoscelesTriangle + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**triangleType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Mammal.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Mammal.md new file mode 100644 index 00000000000..891bc30d288 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Mammal.md @@ -0,0 +1,26 @@ + + +# Mammal + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**hasBaleen** | **Boolean** | | [optional] +**hasTeeth** | **Boolean** | | [optional] +**className** | **String** | | +**type** | [**TypeEnum**](#TypeEnum) | | [optional] + + + +## Enum: TypeEnum + +Name | Value +---- | ----- +PLAINS | "plains" +MOUNTAIN | "mountain" +GREVYS | "grevys" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/MapTest.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/MapTest.md new file mode 100644 index 00000000000..16f3ab93449 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/MapTest.md @@ -0,0 +1,25 @@ + + +# MapTest + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | **Map<String, Map<String, String>>** | | [optional] +**mapOfEnumString** | [**Map<String, InnerEnum>**](#Map<String, InnerEnum>) | | [optional] +**directMap** | **Map<String, Boolean>** | | [optional] +**indirectMap** | **Map<String, Boolean>** | | [optional] + + + +## Enum: Map<String, InnerEnum> + +Name | Value +---- | ----- +UPPER | "UPPER" +LOWER | "lower" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..8bc2ed1571f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,15 @@ + + +# MixedPropertiesAndAdditionalPropertiesClass + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **UUID** | | [optional] +**dateTime** | **OffsetDateTime** | | [optional] +**map** | [**Map<String, Animal>**](Animal.md) | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Model200Response.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Model200Response.md new file mode 100644 index 00000000000..91c45e49421 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Model200Response.md @@ -0,0 +1,15 @@ + + +# Model200Response + +Model for testing model name starting with number + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | [optional] +**propertyClass** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ModelApiResponse.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ModelApiResponse.md new file mode 100644 index 00000000000..aca98405e37 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ModelApiResponse.md @@ -0,0 +1,15 @@ + + +# ModelApiResponse + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Integer** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ModelReturn.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ModelReturn.md new file mode 100644 index 00000000000..3684358a040 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ModelReturn.md @@ -0,0 +1,14 @@ + + +# ModelReturn + +Model for testing reserved words + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Integer** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Name.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Name.md new file mode 100644 index 00000000000..219628217ca --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Name.md @@ -0,0 +1,17 @@ + + +# Name + +Model for testing model name same as property name + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Integer** | | +**snakeCase** | **Integer** | | [optional] [readonly] +**property** | **String** | | [optional] +**_123number** | **Integer** | | [optional] [readonly] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/NullableClass.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/NullableClass.md new file mode 100644 index 00000000000..c8152be3d31 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/NullableClass.md @@ -0,0 +1,24 @@ + + +# NullableClass + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integerProp** | **Integer** | | [optional] +**numberProp** | **BigDecimal** | | [optional] +**booleanProp** | **Boolean** | | [optional] +**stringProp** | **String** | | [optional] +**dateProp** | **LocalDate** | | [optional] +**datetimeProp** | **OffsetDateTime** | | [optional] +**arrayNullableProp** | **List<Object>** | | [optional] +**arrayAndItemsNullableProp** | **List<Object>** | | [optional] +**arrayItemsNullable** | **List<Object>** | | [optional] +**objectNullableProp** | **Map<String, Object>** | | [optional] +**objectAndItemsNullableProp** | **Map<String, Object>** | | [optional] +**objectItemsNullable** | **Map<String, Object>** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/NullableShape.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/NullableShape.md new file mode 100644 index 00000000000..0b0307116e2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/NullableShape.md @@ -0,0 +1,15 @@ + + +# NullableShape + +The value may be a shape or the 'null' value. The 'nullable' attribute was introduced in OAS schema >= 3.0 and has been deprecated in OAS schema >= 3.1. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**quadrilateralType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/NumberOnly.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/NumberOnly.md new file mode 100644 index 00000000000..26c0b18032e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/NumberOnly.md @@ -0,0 +1,13 @@ + + +# NumberOnly + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | **BigDecimal** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ObjectWithDeprecatedFields.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ObjectWithDeprecatedFields.md new file mode 100644 index 00000000000..be55a96c3b7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ObjectWithDeprecatedFields.md @@ -0,0 +1,16 @@ + + +# ObjectWithDeprecatedFields + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **String** | | [optional] +**id** | **BigDecimal** | | [optional] +**deprecatedRef** | [**DeprecatedObject**](DeprecatedObject.md) | | [optional] +**bars** | **List<String>** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Order.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Order.md new file mode 100644 index 00000000000..fa708e88241 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Order.md @@ -0,0 +1,28 @@ + + +# Order + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Integer** | | [optional] +**shipDate** | **OffsetDateTime** | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + + +## Enum: StatusEnum + +Name | Value +---- | ----- +PLACED | "placed" +APPROVED | "approved" +DELIVERED | "delivered" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterComposite.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterComposite.md new file mode 100644 index 00000000000..7274cb07593 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterComposite.md @@ -0,0 +1,15 @@ + + +# OuterComposite + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**myNumber** | **BigDecimal** | | [optional] +**myString** | **String** | | [optional] +**myBoolean** | **Boolean** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnum.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnum.md new file mode 100644 index 00000000000..1f9b723eb8e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnum.md @@ -0,0 +1,15 @@ + + +# OuterEnum + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumDefaultValue.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumDefaultValue.md new file mode 100644 index 00000000000..cbc7f4ba54d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumDefaultValue.md @@ -0,0 +1,15 @@ + + +# OuterEnumDefaultValue + +## Enum + + +* `PLACED` (value: `"placed"`) + +* `APPROVED` (value: `"approved"`) + +* `DELIVERED` (value: `"delivered"`) + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumInteger.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumInteger.md new file mode 100644 index 00000000000..f71dea30ad0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumInteger.md @@ -0,0 +1,15 @@ + + +# OuterEnumInteger + +## Enum + + +* `NUMBER_0` (value: `0`) + +* `NUMBER_1` (value: `1`) + +* `NUMBER_2` (value: `2`) + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumIntegerDefaultValue.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumIntegerDefaultValue.md new file mode 100644 index 00000000000..99e6389f427 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/OuterEnumIntegerDefaultValue.md @@ -0,0 +1,15 @@ + + +# OuterEnumIntegerDefaultValue + +## Enum + + +* `NUMBER_0` (value: `0`) + +* `NUMBER_1` (value: `1`) + +* `NUMBER_2` (value: `2`) + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ParentPet.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ParentPet.md new file mode 100644 index 00000000000..ad7e0219665 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ParentPet.md @@ -0,0 +1,12 @@ + + +# ParentPet + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Pet.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Pet.md new file mode 100644 index 00000000000..8aab7453687 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Pet.md @@ -0,0 +1,28 @@ + + +# Pet + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **List<String>** | | +**tags** | [**List<Tag>**](Tag.md) | | [optional] +**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] + + + +## Enum: StatusEnum + +Name | Value +---- | ----- +AVAILABLE | "available" +PENDING | "pending" +SOLD | "sold" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/PetApi.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/PetApi.md new file mode 100644 index 00000000000..cca26664dea --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/PetApi.md @@ -0,0 +1,630 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**uploadFileWithRequiredFile**](PetApi.md#uploadFileWithRequiredFile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) + + + +# **addPet** +> addPet(pet) + +Add a new pet to the store + +### 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.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.addPet(pet); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**405** | Invalid input | - | + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + +### 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.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | Pet id to delete + String apiKey = "apiKey_example"; // String | + try { + apiInstance.deletePet(petId, apiKey); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid pet value | - | + + +# **findPetsByStatus** +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### 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.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List status = Arrays.asList("available"); // List | Status values that need to be considered for filter + try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid status value | - | + + +# **findPetsByTags** +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### 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.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List tags = Arrays.asList(); // List | Tags to filter by + try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<String>**](String.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid tag value | - | + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### 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.models.*; +import org.openapitools.client.api.PetApi; + +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"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to return + try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid ID supplied | - | +**404** | Pet not found | - | + + +# **updatePet** +> updatePet(pet) + +Update an existing pet + +### 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.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + apiInstance.updatePet(pet); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + +[http_signature_test](../README.md#http_signature_test), [petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid ID supplied | - | +**404** | Pet not found | - | +**405** | Validation exception | - | + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### 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.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet that needs to be updated + String name = "name_example"; // String | Updated name of the pet + String status = "status_example"; // String | Updated status of the pet + try { + apiInstance.updatePetWithForm(petId, name, status); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**405** | Invalid input | - | + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### 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.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + File file = new File("/path/to/file"); // File | file to upload + try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, file); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + + +# **uploadFileWithRequiredFile** +> ModelApiResponse uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata) + +uploads an image (required) + +### 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.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + File requiredFile = new File("/path/to/file"); // File | file to upload + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + try { + ModelApiResponse result = apiInstance.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFileWithRequiredFile"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **requiredFile** | **File**| file to upload | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Pig.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Pig.md new file mode 100644 index 00000000000..b3b94d03563 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Pig.md @@ -0,0 +1,13 @@ + + +# Pig + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Quadrilateral.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Quadrilateral.md new file mode 100644 index 00000000000..208f4899d27 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Quadrilateral.md @@ -0,0 +1,14 @@ + + +# Quadrilateral + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**quadrilateralType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/QuadrilateralInterface.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/QuadrilateralInterface.md new file mode 100644 index 00000000000..a26b2710779 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/QuadrilateralInterface.md @@ -0,0 +1,13 @@ + + +# QuadrilateralInterface + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**quadrilateralType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ReadOnlyFirst.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..a329bf4419a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ReadOnlyFirst.md @@ -0,0 +1,14 @@ + + +# ReadOnlyFirst + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**baz** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ScaleneTriangle.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ScaleneTriangle.md new file mode 100644 index 00000000000..f49fe5a12f3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ScaleneTriangle.md @@ -0,0 +1,14 @@ + + +# ScaleneTriangle + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**triangleType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Shape.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Shape.md new file mode 100644 index 00000000000..ff25b8670e9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Shape.md @@ -0,0 +1,14 @@ + + +# Shape + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**quadrilateralType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ShapeInterface.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ShapeInterface.md new file mode 100644 index 00000000000..f8b65a8a972 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ShapeInterface.md @@ -0,0 +1,13 @@ + + +# ShapeInterface + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/ShapeOrNull.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ShapeOrNull.md new file mode 100644 index 00000000000..633d68d670c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/ShapeOrNull.md @@ -0,0 +1,15 @@ + + +# ShapeOrNull + +The value may be a shape or the 'null' value. This is introduced in OAS schema >= 3.1. + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**quadrilateralType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/SimpleQuadrilateral.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/SimpleQuadrilateral.md new file mode 100644 index 00000000000..c2cf751d1b8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/SimpleQuadrilateral.md @@ -0,0 +1,14 @@ + + +# SimpleQuadrilateral + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**quadrilateralType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/SpecialModelName.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/SpecialModelName.md new file mode 100644 index 00000000000..352611142df --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/SpecialModelName.md @@ -0,0 +1,14 @@ + + +# SpecialModelName + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**$specialPropertyName** | **Long** | | [optional] +**specialModelName** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/StoreApi.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/StoreApi.md new file mode 100644 index 00000000000..270388f5e44 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/StoreApi.md @@ -0,0 +1,264 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + String orderId = "orderId_example"; // String | ID of the order that needs to be deleted + try { + apiInstance.deleteOrder(orderId); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid ID supplied | - | +**404** | Order not found | - | + + +# **getInventory** +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### 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.models.*; +import org.openapitools.client.api.StoreApi; + +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"); + + StoreApi apiInstance = new StoreApi(defaultClient); + try { + Map result = apiInstance.getInventory(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + 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 + +**Map<String, Integer>** + +### 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 | - | + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of pet that needs to be fetched + try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid ID supplied | - | +**404** | Order not found | - | + + +# **placeOrder** +> Order placeOrder(order) + +Place an order for a pet + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Order order = new Order(); // Order | order placed for purchasing the pet + try { + Order result = apiInstance.placeOrder(order); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid Order | - | + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/StringBooleanMap.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/StringBooleanMap.md new file mode 100644 index 00000000000..cac7afc80e0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/StringBooleanMap.md @@ -0,0 +1,9 @@ + +# StringBooleanMap + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Tag.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Tag.md new file mode 100644 index 00000000000..70d36f5d0d4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Tag.md @@ -0,0 +1,14 @@ + + +# Tag + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Triangle.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Triangle.md new file mode 100644 index 00000000000..0a3af5adc4f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Triangle.md @@ -0,0 +1,14 @@ + + +# Triangle + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**shapeType** | **String** | | +**triangleType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/TriangleInterface.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/TriangleInterface.md new file mode 100644 index 00000000000..525872029f5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/TriangleInterface.md @@ -0,0 +1,13 @@ + + +# TriangleInterface + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**triangleType** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/TypeHolderDefault.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/TypeHolderDefault.md new file mode 100644 index 00000000000..8340befcae5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/TypeHolderDefault.md @@ -0,0 +1,17 @@ + + +# TypeHolderDefault + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | +**numberItem** | **BigDecimal** | | +**integerItem** | **Integer** | | +**boolItem** | **Boolean** | | +**arrayItem** | **List<Integer>** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/TypeHolderExample.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/TypeHolderExample.md new file mode 100644 index 00000000000..2396fdf1765 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/TypeHolderExample.md @@ -0,0 +1,18 @@ + + +# TypeHolderExample + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | +**numberItem** | **BigDecimal** | | +**floatItem** | **Float** | | +**integerItem** | **Integer** | | +**boolItem** | **Boolean** | | +**arrayItem** | **List<Integer>** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/User.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/User.md new file mode 100644 index 00000000000..c29bce5c126 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/User.md @@ -0,0 +1,24 @@ + + +# User + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Integer** | User Status | [optional] +**objectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] +**objectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] +**anyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] +**anyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/UserApi.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/UserApi.md new file mode 100644 index 00000000000..26a0642e323 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/UserApi.md @@ -0,0 +1,501 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(user) + +Create user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + User user = new User(); // User | Created user object + try { + apiInstance.createUser(user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**0** | successful operation | - | + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(user) + +Creates list of users with given input array + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List user = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithArrayInput(user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**0** | successful operation | - | + + +# **createUsersWithListInput** +> createUsersWithListInput(user) + +Creates list of users with given input array + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + List user = Arrays.asList(); // List | List of user object + try { + apiInstance.createUsersWithListInput(user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**0** | successful operation | - | + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be deleted + try { + apiInstance.deleteUser(username); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid username supplied | - | +**404** | User not found | - | + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. + try { + User result = apiInstance.getUserByName(username); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | +**400** | Invalid username supplied | - | +**404** | User not found | - | + + +# **loginUser** +> String loginUser(username, password) + +Logs user into the system + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The user name for login + String password = "password_example"; // String | The password for login in clear text + try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
    * X-Expires-After - date in UTC when token expires
    | +**400** | Invalid username/password supplied | - | + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + try { + apiInstance.logoutUser(); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + 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 + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**0** | successful operation | - | + + +# **updateUser** +> updateUser(username, user) + +Updated user + +This can only be done by the logged in user. + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | name that need to be deleted + User user = new User(); // User | Updated user object + try { + apiInstance.updateUser(username, user); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**400** | Invalid user supplied | - | +**404** | User not found | - | + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Whale.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Whale.md new file mode 100644 index 00000000000..87470ae5fac --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Whale.md @@ -0,0 +1,15 @@ + + +# Whale + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**hasBaleen** | **Boolean** | | [optional] +**hasTeeth** | **Boolean** | | [optional] +**className** | **String** | | + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/XmlItem.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/XmlItem.md new file mode 100644 index 00000000000..8c184da283d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/XmlItem.md @@ -0,0 +1,41 @@ + + +# XmlItem + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**attributeString** | **String** | | [optional] +**attributeNumber** | **BigDecimal** | | [optional] +**attributeInteger** | **Integer** | | [optional] +**attributeBoolean** | **Boolean** | | [optional] +**wrappedArray** | **List<Integer>** | | [optional] +**nameString** | **String** | | [optional] +**nameNumber** | **BigDecimal** | | [optional] +**nameInteger** | **Integer** | | [optional] +**nameBoolean** | **Boolean** | | [optional] +**nameArray** | **List<Integer>** | | [optional] +**nameWrappedArray** | **List<Integer>** | | [optional] +**prefixString** | **String** | | [optional] +**prefixNumber** | **BigDecimal** | | [optional] +**prefixInteger** | **Integer** | | [optional] +**prefixBoolean** | **Boolean** | | [optional] +**prefixArray** | **List<Integer>** | | [optional] +**prefixWrappedArray** | **List<Integer>** | | [optional] +**namespaceString** | **String** | | [optional] +**namespaceNumber** | **BigDecimal** | | [optional] +**namespaceInteger** | **Integer** | | [optional] +**namespaceBoolean** | **Boolean** | | [optional] +**namespaceArray** | **List<Integer>** | | [optional] +**namespaceWrappedArray** | **List<Integer>** | | [optional] +**prefixNsString** | **String** | | [optional] +**prefixNsNumber** | **BigDecimal** | | [optional] +**prefixNsInteger** | **Integer** | | [optional] +**prefixNsBoolean** | **Boolean** | | [optional] +**prefixNsArray** | **List<Integer>** | | [optional] +**prefixNsWrappedArray** | **List<Integer>** | | [optional] + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/docs/Zebra.md b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Zebra.md new file mode 100644 index 00000000000..eafe1861f2b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/docs/Zebra.md @@ -0,0 +1,24 @@ + + +# Zebra + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**type** | [**TypeEnum**](#TypeEnum) | | [optional] +**className** | **String** | | + + + +## Enum: TypeEnum + +Name | Value +---- | ----- +PLAINS | "plains" +MOUNTAIN | "mountain" +GREVYS | "grevys" + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/git_push.sh b/samples/client/petstore/java/okhttp-gson-nextgen/git_push.sh new file mode 100644 index 00000000000..f53a75d4fab --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/git_push.sh @@ -0,0 +1,57 @@ +#!/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-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/gradle.properties b/samples/client/petstore/java/okhttp-gson-nextgen/gradle.properties new file mode 100644 index 00000000000..a3408578278 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/gradle.properties @@ -0,0 +1,6 @@ +# This file is automatically generated by OpenAPI Generator (https://github.com/openAPITools/openapi-generator). +# To include other gradle properties as part of the code generation process, please use the `gradleProperties` option. +# +# Gradle properties reference: https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties +# For example, uncomment below to build for Android +#target = android diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/java/okhttp-gson-nextgen/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000000000000000000000000000000000000..7454180f2ae8848c63b8b4dea2cb829da983f2fa GIT binary patch literal 59536 zcma&NbC71ylI~qywr$(CZQJHswz}-9F59+k+g;UV+cs{`J?GrGXYR~=-ydruB3JCa zB64N^cILAcWk5iofq)<(fq;O7{th4@;QxID0)qN`mJ?GIqLY#rX8-|G{5M0pdVW5^ zzXk$-2kQTAC?_N@B`&6-N-rmVFE=$QD?>*=4<|!MJu@}isLc4AW#{m2if&A5T5g&~ ziuMQeS*U5sL6J698wOd)K@oK@1{peP5&Esut<#VH^u)gp`9H4)`uE!2$>RTctN+^u z=ASkePDZA-X8)rp%D;p*~P?*a_=*Kwc<^>QSH|^<0>o37lt^+Mj1;4YvJ(JR-Y+?%Nu}JAYj5 z_Qc5%Ao#F?q32i?ZaN2OSNhWL;2oDEw_({7ZbgUjna!Fqn3NzLM@-EWFPZVmc>(fZ z0&bF-Ch#p9C{YJT9Rcr3+Y_uR^At1^BxZ#eo>$PLJF3=;t_$2|t+_6gg5(j{TmjYU zK12c&lE?Eh+2u2&6Gf*IdKS&6?rYbSEKBN!rv{YCm|Rt=UlPcW9j`0o6{66#y5t9C zruFA2iKd=H%jHf%ypOkxLnO8#H}#Zt{8p!oi6)7#NqoF({t6|J^?1e*oxqng9Q2Cc zg%5Vu!em)}Yuj?kaP!D?b?(C*w!1;>R=j90+RTkyEXz+9CufZ$C^umX^+4|JYaO<5 zmIM3#dv`DGM;@F6;(t!WngZSYzHx?9&$xEF70D1BvfVj<%+b#)vz)2iLCrTeYzUcL z(OBnNoG6Le%M+@2oo)&jdOg=iCszzv59e zDRCeaX8l1hC=8LbBt|k5?CXgep=3r9BXx1uR8!p%Z|0+4Xro=xi0G!e{c4U~1j6!) zH6adq0}#l{%*1U(Cb%4AJ}VLWKBPi0MoKFaQH6x?^hQ!6em@993xdtS%_dmevzeNl z(o?YlOI=jl(`L9^ z0O+H9k$_@`6L13eTT8ci-V0ljDMD|0ifUw|Q-Hep$xYj0hTO@0%IS^TD4b4n6EKDG z??uM;MEx`s98KYN(K0>c!C3HZdZ{+_53DO%9k5W%pr6yJusQAv_;IA}925Y%;+!tY z%2k!YQmLLOr{rF~!s<3-WEUs)`ix_mSU|cNRBIWxOox_Yb7Z=~Q45ZNe*u|m^|)d* zog=i>`=bTe!|;8F+#H>EjIMcgWcG2ORD`w0WD;YZAy5#s{65~qfI6o$+Ty&-hyMyJ z3Ra~t>R!p=5ZpxA;QkDAoPi4sYOP6>LT+}{xp}tk+<0k^CKCFdNYG(Es>p0gqD)jP zWOeX5G;9(m@?GOG7g;e74i_|SmE?`B2i;sLYwRWKLy0RLW!Hx`=!LH3&k=FuCsM=9M4|GqzA)anEHfxkB z?2iK-u(DC_T1};KaUT@3nP~LEcENT^UgPvp!QC@Dw&PVAhaEYrPey{nkcn(ro|r7XUz z%#(=$7D8uP_uU-oPHhd>>^adbCSQetgSG`e$U|7mr!`|bU0aHl_cmL)na-5x1#OsVE#m*+k84Y^+UMeSAa zbrVZHU=mFwXEaGHtXQq`2ZtjfS!B2H{5A<3(nb-6ARVV8kEmOkx6D2x7~-6hl;*-*}2Xz;J#a8Wn;_B5=m zl3dY;%krf?i-Ok^Pal-}4F`{F@TYPTwTEhxpZK5WCpfD^UmM_iYPe}wpE!Djai6_{ z*pGO=WB47#Xjb7!n2Ma)s^yeR*1rTxp`Mt4sfA+`HwZf%!7ZqGosPkw69`Ix5Ku6G z@Pa;pjzV&dn{M=QDx89t?p?d9gna*}jBly*#1!6}5K<*xDPJ{wv4& zM$17DFd~L*Te3A%yD;Dp9UGWTjRxAvMu!j^Tbc}2v~q^59d4bz zvu#!IJCy(BcWTc`;v$9tH;J%oiSJ_i7s;2`JXZF+qd4C)vY!hyCtl)sJIC{ebI*0> z@x>;EzyBv>AI-~{D6l6{ST=em*U( z(r$nuXY-#CCi^8Z2#v#UXOt`dbYN1z5jzNF2 z411?w)whZrfA20;nl&C1Gi+gk<`JSm+{|*2o<< zqM#@z_D`Cn|0H^9$|Tah)0M_X4c37|KQ*PmoT@%xHc3L1ZY6(p(sNXHa&49Frzto& zR`c~ClHpE~4Z=uKa5S(-?M8EJ$zt0&fJk~p$M#fGN1-y$7!37hld`Uw>Urri(DxLa;=#rK0g4J)pXMC zxzraOVw1+kNWpi#P=6(qxf`zSdUC?D$i`8ZI@F>k6k zz21?d+dw7b&i*>Kv5L(LH-?J%@WnqT7j#qZ9B>|Zl+=> z^U-pV@1y_ptHo4hl^cPRWewbLQ#g6XYQ@EkiP z;(=SU!yhjHp%1&MsU`FV1Z_#K1&(|5n(7IHbx&gG28HNT)*~-BQi372@|->2Aw5It z0CBpUcMA*QvsPy)#lr!lIdCi@1k4V2m!NH)%Px(vu-r(Q)HYc!p zJ^$|)j^E#q#QOgcb^pd74^JUi7fUmMiNP_o*lvx*q%_odv49Dsv$NV;6J z9GOXKomA{2Pb{w}&+yHtH?IkJJu~}Z?{Uk++2mB8zyvh*xhHKE``99>y#TdD z&(MH^^JHf;g(Tbb^&8P*;_i*2&fS$7${3WJtV7K&&(MBV2~)2KB3%cWg#1!VE~k#C z!;A;?p$s{ihyojEZz+$I1)L}&G~ml=udD9qh>Tu(ylv)?YcJT3ihapi!zgPtWb*CP zlLLJSRCj-^w?@;RU9aL2zDZY1`I3d<&OMuW=c3$o0#STpv_p3b9Wtbql>w^bBi~u4 z3D8KyF?YE?=HcKk!xcp@Cigvzy=lnFgc^9c%(^F22BWYNAYRSho@~*~S)4%AhEttv zvq>7X!!EWKG?mOd9&n>vvH1p4VzE?HCuxT-u+F&mnsfDI^}*-d00-KAauEaXqg3k@ zy#)MGX!X;&3&0s}F3q40ZmVM$(H3CLfpdL?hB6nVqMxX)q=1b}o_PG%r~hZ4gUfSp zOH4qlEOW4OMUc)_m)fMR_rl^pCfXc{$fQbI*E&mV77}kRF z&{<06AJyJ!e863o-V>FA1a9Eemx6>^F$~9ppt()ZbPGfg_NdRXBWoZnDy2;#ODgf! zgl?iOcF7Meo|{AF>KDwTgYrJLb$L2%%BEtO>T$C?|9bAB&}s;gI?lY#^tttY&hfr# zKhC+&b-rpg_?~uVK%S@mQleU#_xCsvIPK*<`E0fHE1&!J7!xD#IB|SSPW6-PyuqGn3^M^Rz%WT{e?OI^svARX&SAdU77V(C~ zM$H{Kg59op{<|8ry9ecfP%=kFm(-!W&?U0@<%z*+!*<e0XesMxRFu9QnGqun6R_%T+B%&9Dtk?*d$Q zb~>84jEAPi@&F@3wAa^Lzc(AJz5gsfZ7J53;@D<;Klpl?sK&u@gie`~vTsbOE~Cd4 z%kr56mI|#b(Jk&;p6plVwmNB0H@0SmgdmjIn5Ne@)}7Vty(yb2t3ev@22AE^s!KaN zyQ>j+F3w=wnx7w@FVCRe+`vUH)3gW%_72fxzqX!S&!dchdkRiHbXW1FMrIIBwjsai8`CB2r4mAbwp%rrO>3B$Zw;9=%fXI9B{d(UzVap7u z6piC-FQ)>}VOEuPpuqznpY`hN4dGa_1Xz9rVg(;H$5Te^F0dDv*gz9JS<|>>U0J^# z6)(4ICh+N_Q`Ft0hF|3fSHs*?a=XC;e`sJaU9&d>X4l?1W=|fr!5ShD|nv$GK;j46@BV6+{oRbWfqOBRb!ir88XD*SbC(LF}I1h#6@dvK%Toe%@ zhDyG$93H8Eu&gCYddP58iF3oQH*zLbNI;rN@E{T9%A8!=v#JLxKyUe}e}BJpB{~uN zqgxRgo0*-@-iaHPV8bTOH(rS(huwK1Xg0u+e!`(Irzu@Bld&s5&bWgVc@m7;JgELd zimVs`>vQ}B_1(2#rv#N9O`fJpVfPc7V2nv34PC);Dzbb;p!6pqHzvy?2pD&1NE)?A zt(t-ucqy@wn9`^MN5apa7K|L=9>ISC>xoc#>{@e}m#YAAa1*8-RUMKwbm|;5p>T`Z zNf*ph@tnF{gmDa3uwwN(g=`Rh)4!&)^oOy@VJaK4lMT&5#YbXkl`q?<*XtsqD z9PRK6bqb)fJw0g-^a@nu`^?71k|m3RPRjt;pIkCo1{*pdqbVs-Yl>4E>3fZx3Sv44grW=*qdSoiZ9?X0wWyO4`yDHh2E!9I!ZFi zVL8|VtW38}BOJHW(Ax#KL_KQzarbuE{(%TA)AY)@tY4%A%P%SqIU~8~-Lp3qY;U-} z`h_Gel7;K1h}7$_5ZZT0&%$Lxxr-<89V&&TCsu}LL#!xpQ1O31jaa{U34~^le*Y%L za?7$>Jk^k^pS^_M&cDs}NgXlR>16AHkSK-4TRaJSh#h&p!-!vQY%f+bmn6x`4fwTp z$727L^y`~!exvmE^W&#@uY!NxJi`g!i#(++!)?iJ(1)2Wk;RN zFK&O4eTkP$Xn~4bB|q8y(btx$R#D`O@epi4ofcETrx!IM(kWNEe42Qh(8*KqfP(c0 zouBl6>Fc_zM+V;F3znbo{x#%!?mH3`_ANJ?y7ppxS@glg#S9^MXu|FM&ynpz3o&Qh z2ujAHLF3($pH}0jXQsa#?t--TnF1P73b?4`KeJ9^qK-USHE)4!IYgMn-7z|=ALF5SNGkrtPG@Y~niUQV2?g$vzJN3nZ{7;HZHzWAeQ;5P|@Tl3YHpyznGG4-f4=XflwSJY+58-+wf?~Fg@1p1wkzuu-RF3j2JX37SQUc? zQ4v%`V8z9ZVZVqS8h|@@RpD?n0W<=hk=3Cf8R?d^9YK&e9ZybFY%jdnA)PeHvtBe- zhMLD+SSteHBq*q)d6x{)s1UrsO!byyLS$58WK;sqip$Mk{l)Y(_6hEIBsIjCr5t>( z7CdKUrJTrW%qZ#1z^n*Lb8#VdfzPw~OIL76aC+Rhr<~;4Tl!sw?Rj6hXj4XWa#6Tp z@)kJ~qOV)^Rh*-?aG>ic2*NlC2M7&LUzc9RT6WM%Cpe78`iAowe!>(T0jo&ivn8-7 zs{Qa@cGy$rE-3AY0V(l8wjI^uB8Lchj@?L}fYal^>T9z;8juH@?rG&g-t+R2dVDBe zq!K%{e-rT5jX19`(bP23LUN4+_zh2KD~EAYzhpEO3MUG8@}uBHH@4J zd`>_(K4q&>*k82(dDuC)X6JuPrBBubOg7qZ{?x!r@{%0);*`h*^F|%o?&1wX?Wr4b z1~&cy#PUuES{C#xJ84!z<1tp9sfrR(i%Tu^jnXy;4`Xk;AQCdFC@?V%|; zySdC7qS|uQRcH}EFZH%mMB~7gi}a0utE}ZE_}8PQH8f;H%PN41Cb9R%w5Oi5el^fd z$n{3SqLCnrF##x?4sa^r!O$7NX!}&}V;0ZGQ&K&i%6$3C_dR%I7%gdQ;KT6YZiQrW zk%q<74oVBV>@}CvJ4Wj!d^?#Zwq(b$E1ze4$99DuNg?6t9H}k_|D7KWD7i0-g*EO7 z;5{hSIYE4DMOK3H%|f5Edx+S0VI0Yw!tsaRS2&Il2)ea^8R5TG72BrJue|f_{2UHa z@w;^c|K3da#$TB0P3;MPlF7RuQeXT$ zS<<|C0OF(k)>fr&wOB=gP8!Qm>F41u;3esv7_0l%QHt(~+n; zf!G6%hp;Gfa9L9=AceiZs~tK+Tf*Wof=4!u{nIO90jH@iS0l+#%8=~%ASzFv7zqSB^?!@N7)kp0t&tCGLmzXSRMRyxCmCYUD2!B`? zhs$4%KO~m=VFk3Buv9osha{v+mAEq=ik3RdK@;WWTV_g&-$U4IM{1IhGX{pAu%Z&H zFfwCpUsX%RKg);B@7OUzZ{Hn{q6Vv!3#8fAg!P$IEx<0vAx;GU%}0{VIsmFBPq_mb zpe^BChDK>sc-WLKl<6 zwbW|e&d&dv9Wu0goueyu>(JyPx1mz0v4E?cJjFuKF71Q1)AL8jHO$!fYT3(;U3Re* zPPOe%*O+@JYt1bW`!W_1!mN&=w3G9ru1XsmwfS~BJ))PhD(+_J_^N6j)sx5VwbWK| zwRyC?W<`pOCY)b#AS?rluxuuGf-AJ=D!M36l{ua?@SJ5>e!IBr3CXIxWw5xUZ@Xrw z_R@%?{>d%Ld4p}nEsiA@v*nc6Ah!MUs?GA7e5Q5lPpp0@`%5xY$C;{%rz24$;vR#* zBP=a{)K#CwIY%p} zXVdxTQ^HS@O&~eIftU+Qt^~(DGxrdi3k}DdT^I7Iy5SMOp$QuD8s;+93YQ!OY{eB24%xY7ml@|M7I(Nb@K_-?F;2?et|CKkuZK_>+>Lvg!>JE~wN`BI|_h6$qi!P)+K-1Hh(1;a`os z55)4Q{oJiA(lQM#;w#Ta%T0jDNXIPM_bgESMCDEg6rM33anEr}=|Fn6)|jBP6Y}u{ zv9@%7*#RI9;fv;Yii5CI+KrRdr0DKh=L>)eO4q$1zmcSmglsV`*N(x=&Wx`*v!!hn6X-l0 zP_m;X??O(skcj+oS$cIdKhfT%ABAzz3w^la-Ucw?yBPEC+=Pe_vU8nd-HV5YX6X8r zZih&j^eLU=%*;VzhUyoLF;#8QsEfmByk+Y~caBqSvQaaWf2a{JKB9B>V&r?l^rXaC z8)6AdR@Qy_BxQrE2Fk?ewD!SwLuMj@&d_n5RZFf7=>O>hzVE*seW3U?_p|R^CfoY`?|#x9)-*yjv#lo&zP=uI`M?J zbzC<^3x7GfXA4{FZ72{PE*-mNHyy59Q;kYG@BB~NhTd6pm2Oj=_ zizmD?MKVRkT^KmXuhsk?eRQllPo2Ubk=uCKiZ&u3Xjj~<(!M94c)Tez@9M1Gfs5JV z->@II)CDJOXTtPrQudNjE}Eltbjq>6KiwAwqvAKd^|g!exgLG3;wP+#mZYr`cy3#39e653d=jrR-ulW|h#ddHu(m9mFoW~2yE zz5?dB%6vF}+`-&-W8vy^OCxm3_{02royjvmwjlp+eQDzFVEUiyO#gLv%QdDSI#3W* z?3!lL8clTaNo-DVJw@ynq?q!%6hTQi35&^>P85G$TqNt78%9_sSJt2RThO|JzM$iL zg|wjxdMC2|Icc5rX*qPL(coL!u>-xxz-rFiC!6hD1IR%|HSRsV3>Kq~&vJ=s3M5y8SG%YBQ|{^l#LGlg!D?E>2yR*eV%9m$_J6VGQ~AIh&P$_aFbh zULr0Z$QE!QpkP=aAeR4ny<#3Fwyw@rZf4?Ewq`;mCVv}xaz+3ni+}a=k~P+yaWt^L z@w67!DqVf7D%7XtXX5xBW;Co|HvQ8WR1k?r2cZD%U;2$bsM%u8{JUJ5Z0k= zZJARv^vFkmWx15CB=rb=D4${+#DVqy5$C%bf`!T0+epLJLnh1jwCdb*zuCL}eEFvE z{rO1%gxg>1!W(I!owu*mJZ0@6FM(?C+d*CeceZRW_4id*D9p5nzMY&{mWqrJomjIZ z97ZNnZ3_%Hx8dn;H>p8m7F#^2;T%yZ3H;a&N7tm=Lvs&lgJLW{V1@h&6Vy~!+Ffbb zv(n3+v)_D$}dqd!2>Y2B)#<+o}LH#%ogGi2-?xRIH)1!SD)u-L65B&bsJTC=LiaF+YOCif2dUX6uAA|#+vNR z>U+KQekVGon)Yi<93(d!(yw1h3&X0N(PxN2{%vn}cnV?rYw z$N^}_o!XUB!mckL`yO1rnUaI4wrOeQ(+&k?2mi47hzxSD`N#-byqd1IhEoh!PGq>t z_MRy{5B0eKY>;Ao3z$RUU7U+i?iX^&r739F)itdrTpAi-NN0=?^m%?{A9Ly2pVv>Lqs6moTP?T2-AHqFD-o_ znVr|7OAS#AEH}h8SRPQ@NGG47dO}l=t07__+iK8nHw^(AHx&Wb<%jPc$$jl6_p(b$ z)!pi(0fQodCHfM)KMEMUR&UID>}m^(!{C^U7sBDOA)$VThRCI0_+2=( zV8mMq0R(#z;C|7$m>$>`tX+T|xGt(+Y48@ZYu#z;0pCgYgmMVbFb!$?%yhZqP_nhn zy4<#3P1oQ#2b51NU1mGnHP$cf0j-YOgAA}A$QoL6JVLcmExs(kU{4z;PBHJD%_=0F z>+sQV`mzijSIT7xn%PiDKHOujX;n|M&qr1T@rOxTdxtZ!&u&3HHFLYD5$RLQ=heur zb>+AFokUVQeJy-#LP*^)spt{mb@Mqe=A~-4p0b+Bt|pZ+@CY+%x}9f}izU5;4&QFE zO1bhg&A4uC1)Zb67kuowWY4xbo&J=%yoXlFB)&$d*-}kjBu|w!^zbD1YPc0-#XTJr z)pm2RDy%J3jlqSMq|o%xGS$bPwn4AqitC6&e?pqWcjWPt{3I{>CBy;hg0Umh#c;hU3RhCUX=8aR>rmd` z7Orw(5tcM{|-^J?ZAA9KP|)X6n9$-kvr#j5YDecTM6n z&07(nD^qb8hpF0B^z^pQ*%5ePYkv&FabrlI61ntiVp!!C8y^}|<2xgAd#FY=8b*y( zuQOuvy2`Ii^`VBNJB&R!0{hABYX55ooCAJSSevl4RPqEGb)iy_0H}v@vFwFzD%>#I>)3PsouQ+_Kkbqy*kKdHdfkN7NBcq%V{x^fSxgXpg7$bF& zj!6AQbDY(1u#1_A#1UO9AxiZaCVN2F0wGXdY*g@x$ByvUA?ePdide0dmr#}udE%K| z3*k}Vv2Ew2u1FXBaVA6aerI36R&rzEZeDDCl5!t0J=ug6kuNZzH>3i_VN`%BsaVB3 zQYw|Xub_SGf{)F{$ZX5`Jc!X!;eybjP+o$I{Z^Hsj@D=E{MnnL+TbC@HEU2DjG{3-LDGIbq()U87x4eS;JXnSh;lRlJ z>EL3D>wHt-+wTjQF$fGyDO$>d+(fq@bPpLBS~xA~R=3JPbS{tzN(u~m#Po!?H;IYv zE;?8%^vle|%#oux(Lj!YzBKv+Fd}*Ur-dCBoX*t{KeNM*n~ZPYJ4NNKkI^MFbz9!v z4(Bvm*Kc!-$%VFEewYJKz-CQN{`2}KX4*CeJEs+Q(!kI%hN1!1P6iOq?ovz}X0IOi z)YfWpwW@pK08^69#wSyCZkX9?uZD?C^@rw^Y?gLS_xmFKkooyx$*^5#cPqntNTtSG zlP>XLMj2!VF^0k#ole7`-c~*~+_T5ls?x4)ah(j8vo_ zwb%S8qoaZqY0-$ZI+ViIA_1~~rAH7K_+yFS{0rT@eQtTAdz#8E5VpwnW!zJ_^{Utv zlW5Iar3V5t&H4D6A=>?mq;G92;1cg9a2sf;gY9pJDVKn$DYdQlvfXq}zz8#LyPGq@ z+`YUMD;^-6w&r-82JL7mA8&M~Pj@aK!m{0+^v<|t%APYf7`}jGEhdYLqsHW-Le9TL z_hZZ1gbrz7$f9^fAzVIP30^KIz!!#+DRLL+qMszvI_BpOSmjtl$hh;&UeM{ER@INV zcI}VbiVTPoN|iSna@=7XkP&-4#06C};8ajbxJ4Gcq8(vWv4*&X8bM^T$mBk75Q92j z1v&%a;OSKc8EIrodmIiw$lOES2hzGDcjjB`kEDfJe{r}yE6`eZL zEB`9u>Cl0IsQ+t}`-cx}{6jqcANucqIB>Qmga_&<+80E2Q|VHHQ$YlAt{6`Qu`HA3 z03s0-sSlwbvgi&_R8s={6<~M^pGvBNjKOa>tWenzS8s zR>L7R5aZ=mSU{f?ib4Grx$AeFvtO5N|D>9#)ChH#Fny2maHWHOf2G=#<9Myot#+4u zWVa6d^Vseq_0=#AYS(-m$Lp;*8nC_6jXIjEM`omUmtH@QDs3|G)i4j*#_?#UYVZvJ z?YjT-?!4Q{BNun;dKBWLEw2C-VeAz`%?A>p;)PL}TAZn5j~HK>v1W&anteARlE+~+ zj>c(F;?qO3pXBb|#OZdQnm<4xWmn~;DR5SDMxt0UK_F^&eD|KZ=O;tO3vy4@4h^;2 zUL~-z`-P1aOe?|ZC1BgVsL)2^J-&vIFI%q@40w0{jjEfeVl)i9(~bt2z#2Vm)p`V_ z1;6$Ae7=YXk#=Qkd24Y23t&GvRxaOoad~NbJ+6pxqzJ>FY#Td7@`N5xp!n(c!=RE& z&<<@^a$_Ys8jqz4|5Nk#FY$~|FPC0`*a5HH!|Gssa9=~66&xG9)|=pOOJ2KE5|YrR zw!w6K2aC=J$t?L-;}5hn6mHd%hC;p8P|Dgh6D>hGnXPgi;6r+eA=?f72y9(Cf_ho{ zH6#)uD&R=73^$$NE;5piWX2bzR67fQ)`b=85o0eOLGI4c-Tb@-KNi2pz=Ke@SDcPn za$AxXib84`!Sf;Z3B@TSo`Dz7GM5Kf(@PR>Ghzi=BBxK8wRp>YQoXm+iL>H*Jo9M3 z6w&E?BC8AFTFT&Tv8zf+m9<&S&%dIaZ)Aoqkak_$r-2{$d~0g2oLETx9Y`eOAf14QXEQw3tJne;fdzl@wV#TFXSLXM2428F-Q}t+n2g%vPRMUzYPvzQ9f# zu(liiJem9P*?0%V@RwA7F53r~|I!Ty)<*AsMX3J{_4&}{6pT%Tpw>)^|DJ)>gpS~1rNEh z0$D?uO8mG?H;2BwM5a*26^7YO$XjUm40XmBsb63MoR;bJh63J;OngS5sSI+o2HA;W zdZV#8pDpC9Oez&L8loZO)MClRz!_!WD&QRtQxnazhT%Vj6Wl4G11nUk8*vSeVab@N#oJ}`KyJv+8Mo@T1-pqZ1t|?cnaVOd;1(h9 z!$DrN=jcGsVYE-0-n?oCJ^4x)F}E;UaD-LZUIzcD?W^ficqJWM%QLy6QikrM1aKZC zi{?;oKwq^Vsr|&`i{jIphA8S6G4)$KGvpULjH%9u(Dq247;R#l&I0{IhcC|oBF*Al zvLo7Xte=C{aIt*otJD}BUq)|_pdR>{zBMT< z(^1RpZv*l*m*OV^8>9&asGBo8h*_4q*)-eCv*|Pq=XNGrZE)^(SF7^{QE_~4VDB(o zVcPA_!G+2CAtLbl+`=Q~9iW`4ZRLku!uB?;tWqVjB0lEOf}2RD7dJ=BExy=<9wkb- z9&7{XFA%n#JsHYN8t5d~=T~5DcW4$B%3M+nNvC2`0!#@sckqlzo5;hhGi(D9=*A4` z5ynobawSPRtWn&CDLEs3Xf`(8^zDP=NdF~F^s&={l7(aw&EG}KWpMjtmz7j_VLO;@ zM2NVLDxZ@GIv7*gzl1 zjq78tv*8#WSY`}Su0&C;2F$Ze(q>F(@Wm^Gw!)(j;dk9Ad{STaxn)IV9FZhm*n+U} zi;4y*3v%A`_c7a__DJ8D1b@dl0Std3F||4Wtvi)fCcBRh!X9$1x!_VzUh>*S5s!oq z;qd{J_r79EL2wIeiGAqFstWtkfIJpjVh%zFo*=55B9Zq~y0=^iqHWfQl@O!Ak;(o*m!pZqe9 z%U2oDOhR)BvW8&F70L;2TpkzIutIvNQaTjjs5V#8mV4!NQ}zN=i`i@WI1z0eN-iCS z;vL-Wxc^Vc_qK<5RPh(}*8dLT{~GzE{w2o$2kMFaEl&q zP{V=>&3kW7tWaK-Exy{~`v4J0U#OZBk{a9{&)&QG18L@6=bsZ1zC_d{{pKZ-Ey>I> z;8H0t4bwyQqgu4hmO`3|4K{R*5>qnQ&gOfdy?z`XD%e5+pTDzUt3`k^u~SaL&XMe= z9*h#kT(*Q9jO#w2Hd|Mr-%DV8i_1{J1MU~XJ3!WUplhXDYBpJH><0OU`**nIvPIof z|N8@I=wA)sf45SAvx||f?Z5uB$kz1qL3Ky_{%RPdP5iN-D2!p5scq}buuC00C@jom zhfGKm3|f?Z0iQ|K$Z~!`8{nmAS1r+fp6r#YDOS8V*;K&Gs7Lc&f^$RC66O|)28oh`NHy&vq zJh+hAw8+ybTB0@VhWN^0iiTnLsCWbS_y`^gs!LX!Lw{yE``!UVzrV24tP8o;I6-65 z1MUiHw^{bB15tmrVT*7-#sj6cs~z`wk52YQJ*TG{SE;KTm#Hf#a~|<(|ImHH17nNM z`Ub{+J3dMD!)mzC8b(2tZtokKW5pAwHa?NFiso~# z1*iaNh4lQ4TS)|@G)H4dZV@l*Vd;Rw;-;odDhW2&lJ%m@jz+Panv7LQm~2Js6rOW3 z0_&2cW^b^MYW3)@o;neZ<{B4c#m48dAl$GCc=$>ErDe|?y@z`$uq3xd(%aAsX)D%l z>y*SQ%My`yDP*zof|3@_w#cjaW_YW4BdA;#Glg1RQcJGY*CJ9`H{@|D+*e~*457kd z73p<%fB^PV!Ybw@)Dr%(ZJbX}xmCStCYv#K3O32ej{$9IzM^I{6FJ8!(=azt7RWf4 z7ib0UOPqN40X!wOnFOoddd8`!_IN~9O)#HRTyjfc#&MCZ zZAMzOVB=;qwt8gV?{Y2?b=iSZG~RF~uyx18K)IDFLl})G1v@$(s{O4@RJ%OTJyF+Cpcx4jmy|F3euCnMK!P2WTDu5j z{{gD$=M*pH!GGzL%P)V2*ROm>!$Y=z|D`!_yY6e7SU$~a5q8?hZGgaYqaiLnkK%?0 zs#oI%;zOxF@g*@(V4p!$7dS1rOr6GVs6uYCTt2h)eB4?(&w8{#o)s#%gN@BBosRUe z)@P@8_Zm89pr~)b>e{tbPC~&_MR--iB{=)y;INU5#)@Gix-YpgP<-c2Ms{9zuCX|3 z!p(?VaXww&(w&uBHzoT%!A2=3HAP>SDxcljrego7rY|%hxy3XlODWffO_%g|l+7Y_ zqV(xbu)s4lV=l7M;f>vJl{`6qBm>#ZeMA}kXb97Z)?R97EkoI?x6Lp0yu1Z>PS?2{ z0QQ(8D)|lc9CO3B~e(pQM&5(1y&y=e>C^X$`)_&XuaI!IgDTVqt31wX#n+@!a_A0ZQkA zCJ2@M_4Gb5MfCrm5UPggeyh)8 zO9?`B0J#rkoCx(R0I!ko_2?iO@|oRf1;3r+i)w-2&j?=;NVIdPFsB)`|IC0zk6r9c zRrkfxWsiJ(#8QndNJj@{@WP2Ackr|r1VxV{7S&rSU(^)-M8gV>@UzOLXu9K<{6e{T zXJ6b92r$!|lwjhmgqkdswY&}c)KW4A)-ac%sU;2^fvq7gfUW4Bw$b!i@duy1CAxSn z(pyh$^Z=&O-q<{bZUP+$U}=*#M9uVc>CQVgDs4swy5&8RAHZ~$)hrTF4W zPsSa~qYv_0mJnF89RnnJTH`3}w4?~epFl=D(35$ zWa07ON$`OMBOHgCmfO(9RFc<)?$x)N}Jd2A(<*Ll7+4jrRt9w zwGxExUXd9VB#I|DwfxvJ;HZ8Q{37^wDhaZ%O!oO(HpcqfLH%#a#!~;Jl7F5>EX_=8 z{()l2NqPz>La3qJR;_v+wlK>GsHl;uRA8%j`A|yH@k5r%55S9{*Cp%uw6t`qc1!*T za2OeqtQj7sAp#Q~=5Fs&aCR9v>5V+s&RdNvo&H~6FJOjvaj--2sYYBvMq;55%z8^o z|BJDA4vzfow#DO#ZQHh;Oq_{r+qP{R9ox2TOgwQiv7Ow!zjN+A@BN;0tA2lUb#+zO z(^b89eV)D7UVE+h{mcNc6&GtpOqDn_?VAQ)Vob$hlFwW%xh>D#wml{t&Ofmm_d_+; zKDxzdr}`n2Rw`DtyIjrG)eD0vut$}dJAZ0AohZ+ZQdWXn_Z@dI_y=7t3q8x#pDI-K z2VVc&EGq445Rq-j0=U=Zx`oBaBjsefY;%)Co>J3v4l8V(T8H?49_@;K6q#r~Wwppc z4XW0(4k}cP=5ex>-Xt3oATZ~bBWKv)aw|I|Lx=9C1s~&b77idz({&q3T(Y(KbWO?+ zmcZ6?WeUsGk6>km*~234YC+2e6Zxdl~<_g2J|IE`GH%n<%PRv-50; zH{tnVts*S5*_RxFT9eM0z-pksIb^drUq4>QSww=u;UFCv2AhOuXE*V4z?MM`|ABOC4P;OfhS(M{1|c%QZ=!%rQTDFx`+}?Kdx$&FU?Y<$x;j7z=(;Lyz+?EE>ov!8vvMtSzG!nMie zsBa9t8as#2nH}n8xzN%W%U$#MHNXmDUVr@GX{?(=yI=4vks|V)!-W5jHsU|h_&+kY zS_8^kd3jlYqOoiI`ZqBVY!(UfnAGny!FowZWY_@YR0z!nG7m{{)4OS$q&YDyw6vC$ zm4!$h>*|!2LbMbxS+VM6&DIrL*X4DeMO!@#EzMVfr)e4Tagn~AQHIU8?e61TuhcKD zr!F4(kEebk(Wdk-?4oXM(rJwanS>Jc%<>R(siF+>+5*CqJLecP_we33iTFTXr6W^G z7M?LPC-qFHK;E!fxCP)`8rkxZyFk{EV;G-|kwf4b$c1k0atD?85+|4V%YATWMG|?K zLyLrws36p%Qz6{}>7b>)$pe>mR+=IWuGrX{3ZPZXF3plvuv5Huax86}KX*lbPVr}L z{C#lDjdDeHr~?l|)Vp_}T|%$qF&q#U;ClHEPVuS+Jg~NjC1RP=17=aQKGOcJ6B3mp z8?4*-fAD~}sX*=E6!}^u8)+m2j<&FSW%pYr_d|p_{28DZ#Cz0@NF=gC-o$MY?8Ca8 zr5Y8DSR^*urS~rhpX^05r30Ik#2>*dIOGxRm0#0YX@YQ%Mg5b6dXlS!4{7O_kdaW8PFSdj1=ryI-=5$fiieGK{LZ+SX(1b=MNL!q#lN zv98?fqqTUH8r8C7v(cx#BQ5P9W>- zmW93;eH6T`vuJ~rqtIBg%A6>q>gnWb3X!r0wh_q;211+Om&?nvYzL1hhtjB zK_7G3!n7PL>d!kj){HQE zE8(%J%dWLh1_k%gVXTZt zEdT09XSKAx27Ncaq|(vzL3gm83q>6CAw<$fTnMU05*xAe&rDfCiu`u^1)CD<>sx0i z*hr^N_TeN89G(nunZoLBf^81#pmM}>JgD@Nn1l*lN#a=B=9pN%tmvYFjFIoKe_(GF z-26x{(KXdfsQL7Uv6UtDuYwV`;8V3w>oT_I<`Ccz3QqK9tYT5ZQzbop{=I=!pMOCb zCU68`n?^DT%^&m>A%+-~#lvF!7`L7a{z<3JqIlk1$<||_J}vW1U9Y&eX<}l8##6i( zZcTT@2`9(Mecptm@{3A_Y(X`w9K0EwtPq~O!16bq{7c0f7#(3wn-^)h zxV&M~iiF!{-6A@>o;$RzQ5A50kxXYj!tcgme=Qjrbje~;5X2xryU;vH|6bE(8z^<7 zQ>BG7_c*JG8~K7Oe68i#0~C$v?-t@~@r3t2inUnLT(c=URpA9kA8uq9PKU(Ps(LVH zqgcqW>Gm?6oV#AldDPKVRcEyQIdTT`Qa1j~vS{<;SwyTdr&3*t?J)y=M7q*CzucZ&B0M=joT zBbj@*SY;o2^_h*>R0e({!QHF0=)0hOj^B^d*m>SnRrwq>MolNSgl^~r8GR#mDWGYEIJA8B<|{{j?-7p zVnV$zancW3&JVDtVpIlI|5djKq0(w$KxEFzEiiL=h5Jw~4Le23@s(mYyXWL9SX6Ot zmb)sZaly_P%BeX_9 zw&{yBef8tFm+%=--m*J|o~+Xg3N+$IH)t)=fqD+|fEk4AAZ&!wcN5=mi~Vvo^i`}> z#_3ahR}Ju)(Px7kev#JGcSwPXJ2id9%Qd2A#Uc@t8~egZ8;iC{e! z%=CGJOD1}j!HW_sgbi_8suYnn4#Ou}%9u)dXd3huFIb!ytlX>Denx@pCS-Nj$`VO&j@(z!kKSP0hE4;YIP#w9ta=3DO$7f*x zc9M4&NK%IrVmZAe=r@skWD`AEWH=g+r|*13Ss$+{c_R!b?>?UaGXlw*8qDmY#xlR= z<0XFbs2t?8i^G~m?b|!Hal^ZjRjt<@a? z%({Gn14b4-a|#uY^=@iiKH+k?~~wTj5K1A&hU z2^9-HTC)7zpoWK|$JXaBL6C z#qSNYtY>65T@Zs&-0cHeu|RX(Pxz6vTITdzJdYippF zC-EB+n4}#lM7`2Ry~SO>FxhKboIAF#Z{1wqxaCb{#yEFhLuX;Rx(Lz%T`Xo1+a2M}7D+@wol2)OJs$TwtRNJ={( zD@#zTUEE}#Fz#&(EoD|SV#bayvr&E0vzmb%H?o~46|FAcx?r4$N z&67W3mdip-T1RIxwSm_&(%U|+WvtGBj*}t69XVd&ebn>KOuL(7Y8cV?THd-(+9>G7*Nt%T zcH;`p={`SOjaf7hNd(=37Lz3-51;58JffzIPgGs_7xIOsB5p2t&@v1mKS$2D$*GQ6 zM(IR*j4{nri7NMK9xlDy-hJW6sW|ZiDRaFiayj%;(%51DN!ZCCCXz+0Vm#};70nOx zJ#yA0P3p^1DED;jGdPbQWo0WATN=&2(QybbVdhd=Vq*liDk`c7iZ?*AKEYC#SY&2g z&Q(Ci)MJ{mEat$ZdSwTjf6h~roanYh2?9j$CF@4hjj_f35kTKuGHvIs9}Re@iKMxS-OI*`0S z6s)fOtz}O$T?PLFVSeOjSO26$@u`e<>k(OSP!&YstH3ANh>)mzmKGNOwOawq-MPXe zy4xbeUAl6tamnx))-`Gi2uV5>9n(73yS)Ukma4*7fI8PaEwa)dWHs6QA6>$}7?(L8 ztN8M}?{Tf!Zu22J5?2@95&rQ|F7=FK-hihT-vDp!5JCcWrVogEnp;CHenAZ)+E+K5 z$Cffk5sNwD_?4+ymgcHR(5xgt20Z8M`2*;MzOM#>yhk{r3x=EyM226wb&!+j`W<%* zSc&|`8!>dn9D@!pYow~(DsY_naSx7(Z4i>cu#hA5=;IuI88}7f%)bRkuY2B;+9Uep zpXcvFWkJ!mQai63BgNXG26$5kyhZ2&*3Q_tk)Ii4M>@p~_~q_cE!|^A;_MHB;7s#9 zKzMzK{lIxotjc};k67^Xsl-gS!^*m*m6kn|sbdun`O?dUkJ{0cmI0-_2y=lTAfn*Y zKg*A-2sJq)CCJgY0LF-VQvl&6HIXZyxo2#!O&6fOhbHXC?%1cMc6y^*dOS{f$=137Ds1m01qs`>iUQ49JijsaQ( zksqV9@&?il$|4Ua%4!O15>Zy&%gBY&wgqB>XA3!EldQ%1CRSM(pp#k~-pkcCg4LAT zXE=puHbgsw)!xtc@P4r~Z}nTF=D2~j(6D%gTBw$(`Fc=OOQ0kiW$_RDd=hcO0t97h zb86S5r=>(@VGy1&#S$Kg_H@7G^;8Ue)X5Y+IWUi`o;mpvoV)`fcVk4FpcT|;EG!;? zHG^zrVVZOm>1KFaHlaogcWj(v!S)O(Aa|Vo?S|P z5|6b{qkH(USa*Z7-y_Uvty_Z1|B{rTS^qmEMLEYUSk03_Fg&!O3BMo{b^*`3SHvl0 zhnLTe^_vVIdcSHe)SQE}r~2dq)VZJ!aSKR?RS<(9lzkYo&dQ?mubnWmgMM37Nudwo z3Vz@R{=m2gENUE3V4NbIzAA$H1z0pagz94-PTJyX{b$yndsdKptmlKQKaaHj@3=ED zc7L?p@%ui|RegVYutK$64q4pe9+5sv34QUpo)u{1ci?)_7gXQd{PL>b0l(LI#rJmN zGuO+%GO`xneFOOr4EU(Wg}_%bhzUf;d@TU+V*2#}!2OLwg~%D;1FAu=Un>OgjPb3S z7l(riiCwgghC=Lm5hWGf5NdGp#01xQ59`HJcLXbUR3&n%P(+W2q$h2Qd z*6+-QXJ*&Kvk9ht0f0*rO_|FMBALen{j7T1l%=Q>gf#kma zQlg#I9+HB+z*5BMxdesMND`_W;q5|FaEURFk|~&{@qY32N$G$2B=&Po{=!)x5b!#n zxLzblkq{yj05#O7(GRuT39(06FJlalyv<#K4m}+vs>9@q-&31@1(QBv82{}Zkns~K ze{eHC_RDX0#^A*JQTwF`a=IkE6Ze@j#-8Q`tTT?k9`^ZhA~3eCZJ-Jr{~7Cx;H4A3 zcZ+Zj{mzFZbVvQ6U~n>$U2ZotGsERZ@}VKrgGh0xM;Jzt29%TX6_&CWzg+YYMozrM z`nutuS)_0dCM8UVaKRj804J4i%z2BA_8A4OJRQ$N(P9Mfn-gF;4#q788C@9XR0O3< zsoS4wIoyt046d+LnSCJOy@B@Uz*#GGd#+Ln1ek5Dv>(ZtD@tgZlPnZZJGBLr^JK+!$$?A_fA3LOrkoDRH&l7 zcMcD$Hsjko3`-{bn)jPL6E9Ds{WskMrivsUu5apD z?grQO@W7i5+%X&E&p|RBaEZ(sGLR@~(y^BI@lDMot^Ll?!`90KT!JXUhYS`ZgX3jnu@Ja^seA*M5R@f`=`ynQV4rc$uT1mvE?@tz)TN<=&H1%Z?5yjxcpO+6y_R z6EPuPKM5uxKpmZfT(WKjRRNHs@ib)F5WAP7QCADvmCSD#hPz$V10wiD&{NXyEwx5S z6NE`3z!IS^$s7m}PCwQutVQ#~w+V z=+~->DI*bR2j0^@dMr9`p>q^Ny~NrAVxrJtX2DUveic5vM%#N*XO|?YAWwNI$Q)_) zvE|L(L1jP@F%gOGtnlXtIv2&1i8q<)Xfz8O3G^Ea~e*HJsQgBxWL(yuLY+jqUK zRE~`-zklrGog(X}$9@ZVUw!8*=l`6mzYLtsg`AvBYz(cxmAhr^j0~(rzXdiOEeu_p zE$sf2(w(BPAvO5DlaN&uQ$4@p-b?fRs}d7&2UQ4Fh?1Hzu*YVjcndqJLw0#q@fR4u zJCJ}>_7-|QbvOfylj+e^_L`5Ep9gqd>XI3-O?Wp z-gt*P29f$Tx(mtS`0d05nHH=gm~Po_^OxxUwV294BDKT>PHVlC5bndncxGR!n(OOm znsNt@Q&N{TLrmsoKFw0&_M9$&+C24`sIXGWgQaz=kY;S{?w`z^Q0JXXBKFLj0w0U6P*+jPKyZHX9F#b0D1$&(- zrm8PJd?+SrVf^JlfTM^qGDK&-p2Kdfg?f>^%>1n8bu&byH(huaocL>l@f%c*QkX2i znl}VZ4R1en4S&Bcqw?$=Zi7ohqB$Jw9x`aM#>pHc0x z0$!q7iFu zZ`tryM70qBI6JWWTF9EjgG@>6SRzsd}3h+4D8d~@CR07P$LJ}MFsYi-*O%XVvD@yT|rJ+Mk zDllJ7$n0V&A!0flbOf)HE6P_afPWZmbhpliqJuw=-h+r;WGk|ntkWN(8tKlYpq5Ow z(@%s>IN8nHRaYb*^d;M(D$zGCv5C|uqmsDjwy4g=Lz>*OhO3z=)VD}C<65;`89Ye} zSCxrv#ILzIpEx1KdLPlM&%Cctf@FqTKvNPXC&`*H9=l=D3r!GLM?UV zOxa(8ZsB`&+76S-_xuj?G#wXBfDY@Z_tMpXJS7^mp z@YX&u0jYw2A+Z+bD#6sgVK5ZgdPSJV3>{K^4~%HV?rn~4D)*2H!67Y>0aOmzup`{D zzDp3c9yEbGCY$U<8biJ_gB*`jluz1ShUd!QUIQJ$*1;MXCMApJ^m*Fiv88RZ zFopLViw}{$Tyhh_{MLGIE2~sZ)t0VvoW%=8qKZ>h=adTe3QM$&$PO2lfqH@brt!9j ziePM8$!CgE9iz6B<6_wyTQj?qYa;eC^{x_0wuwV~W+^fZmFco-o%wsKSnjXFEx02V zF5C2t)T6Gw$Kf^_c;Ei3G~uC8SM-xyycmXyC2hAVi-IfXqhu$$-C=*|X?R0~hu z8`J6TdgflslhrmDZq1f?GXF7*ALeMmOEpRDg(s*H`4>_NAr`2uqF;k;JQ+8>A|_6ZNsNLECC%NNEb1Y1dP zbIEmNpK)#XagtL4R6BC{C5T(+=yA-(Z|Ap}U-AfZM#gwVpus3(gPn}Q$CExObJ5AC z)ff9Yk?wZ}dZ-^)?cbb9Fw#EjqQ8jxF4G3=L?Ra zg_)0QDMV1y^A^>HRI$x?Op@t;oj&H@1xt4SZ9(kifQ zb59B*`M99Td7@aZ3UWvj1rD0sE)d=BsBuW*KwkCds7ay(7*01_+L}b~7)VHI>F_!{ zyxg-&nCO?v#KOUec0{OOKy+sjWA;8rTE|Lv6I9H?CI?H(mUm8VXGwU$49LGpz&{nQp2}dinE1@lZ1iox6{ghN&v^GZv9J${7WaXj)<0S4g_uiJ&JCZ zr8-hsu`U%N;+9N^@&Q0^kVPB3)wY(rr}p7{p0qFHb3NUUHJb672+wRZs`gd1UjKPX z4o6zljKKA+Kkj?H>Ew63o%QjyBk&1!P22;MkD>sM0=z_s-G{mTixJCT9@_|*(p^bz zJ8?ZZ&;pzV+7#6Mn`_U-)k8Pjg?a;|Oe^us^PoPY$Va~yi8|?+&=y$f+lABT<*pZr zP}D{~Pq1Qyni+@|aP;ixO~mbEW9#c0OU#YbDZIaw=_&$K%Ep2f%hO^&P67hApZe`x zv8b`Mz@?M_7-)b!lkQKk)JXXUuT|B8kJlvqRmRpxtQDgvrHMXC1B$M@Y%Me!BSx3P z#2Eawl$HleZhhTS6Txm>lN_+I`>eV$&v9fOg)%zVn3O5mI*lAl>QcHuW6!Kixmq`X zBCZ*Ck6OYtDiK!N47>jxI&O2a9x7M|i^IagRr-fmrmikEQGgw%J7bO|)*$2FW95O4 zeBs>KR)izRG1gRVL;F*sr8A}aRHO0gc$$j&ds8CIO1=Gwq1%_~E)CWNn9pCtBE}+`Jelk4{>S)M)`Ll=!~gnn1yq^EX(+y*ik@3Ou0qU`IgYi3*doM+5&dU!cho$pZ zn%lhKeZkS72P?Cf68<#kll_6OAO26bIbueZx**j6o;I0cS^XiL`y+>{cD}gd%lux} z)3N>MaE24WBZ}s0ApfdM;5J_Ny}rfUyxfkC``Awo2#sgLnGPewK};dORuT?@I6(5~ z?kE)Qh$L&fwJXzK){iYx!l5$Tt|^D~MkGZPA}(o6f7w~O2G6Vvzdo*a;iXzk$B66$ zwF#;wM7A+(;uFG4+UAY(2`*3XXx|V$K8AYu#ECJYSl@S=uZW$ksfC$~qrrbQj4??z-)uz0QL}>k^?fPnJTPw% zGz)~?B4}u0CzOf@l^um}HZzbaIwPmb<)< zi_3@E9lc)Qe2_`*Z^HH;1CXOceL=CHpHS{HySy3T%<^NrWQ}G0i4e1xm_K3(+~oi$ zoHl9wzb?Z4j#90DtURtjtgvi7uw8DzHYmtPb;?%8vb9n@bszT=1qr)V_>R%s!92_` zfnHQPANx z<#hIjIMm#*(v*!OXtF+w8kLu`o?VZ5k7{`vw{Yc^qYclpUGIM_PBN1+c{#Vxv&E*@ zxg=W2W~JuV{IuRYw3>LSI1)a!thID@R=bU+cU@DbR^_SXY`MC7HOsCN z!dO4OKV7(E_Z8T#8MA1H`99?Z!r0)qKW_#|29X3#Jb+5+>qUidbeP1NJ@)(qi2S-X zao|f0_tl(O+$R|Qwd$H{_ig|~I1fbp_$NkI!0E;Y z6JrnU{1Ra6^on{9gUUB0mwzP3S%B#h0fjo>JvV~#+X0P~JV=IG=yHG$O+p5O3NUgG zEQ}z6BTp^Fie)Sg<){Z&I8NwPR(=mO4joTLHkJ>|Tnk23E(Bo`FSbPc05lF2-+)X? z6vV3*m~IBHTy*^E!<0nA(tCOJW2G4DsH7)BxLV8kICn5lu6@U*R`w)o9;Ro$i8=Q^V%uH8n3q=+Yf;SFRZu z!+F&PKcH#8cG?aSK_Tl@K9P#8o+jry@gdexz&d(Q=47<7nw@e@FFfIRNL9^)1i@;A z28+$Z#rjv-wj#heI|<&J_DiJ*s}xd-f!{J8jfqOHE`TiHHZVIA8CjkNQ_u;Ery^^t zl1I75&u^`1_q)crO+JT4rx|z2ToSC>)Or@-D zy3S>jW*sNIZR-EBsfyaJ+Jq4BQE4?SePtD2+jY8*%FsSLZ9MY>+wk?}}}AFAw)vr{ml)8LUG-y9>^t!{~|sgpxYc0Gnkg`&~R z-pilJZjr@y5$>B=VMdZ73svct%##v%wdX~9fz6i3Q-zOKJ9wso+h?VME7}SjL=!NUG{J?M&i!>ma`eoEa@IX`5G>B1(7;%}M*%-# zfhJ(W{y;>MRz!Ic8=S}VaBKqh;~7KdnGEHxcL$kA-6E~=!hrN*zw9N+_=odt<$_H_8dbo;0=42wcAETPCVGUr~v(`Uai zb{=D!Qc!dOEU6v)2eHSZq%5iqK?B(JlCq%T6av$Cb4Rko6onlG&?CqaX7Y_C_cOC3 zYZ;_oI(}=>_07}Oep&Ws7x7-R)cc8zfe!SYxJYP``pi$FDS)4Fvw5HH=FiU6xfVqIM!hJ;Rx8c0cB7~aPtNH(Nmm5Vh{ibAoU#J6 zImRCr?(iyu_4W_6AWo3*vxTPUw@vPwy@E0`(>1Qi=%>5eSIrp^`` zK*Y?fK_6F1W>-7UsB)RPC4>>Ps9)f+^MqM}8AUm@tZ->j%&h1M8s*s!LX5&WxQcAh z8mciQej@RPm?660%>{_D+7er>%zX_{s|$Z+;G7_sfNfBgY(zLB4Ey}J9F>zX#K0f6 z?dVNIeEh?EIShmP6>M+d|0wMM85Sa4diw1hrg|ITJ}JDg@o8y>(rF9mXk5M z2@D|NA)-7>wD&wF;S_$KS=eE84`BGw3g0?6wGxu8ys4rwI?9U=*^VF22t3%mbGeOh z`!O-OpF7#Vceu~F`${bW0nYVU9ecmk31V{tF%iv&5hWofC>I~cqAt@u6|R+|HLMMX zVxuSlMFOK_EQ86#E8&KwxIr8S9tj_goWtLv4f@!&h8;Ov41{J~496vp9vX=(LK#j! zAwi*21RAV-LD>9Cw3bV_9X(X3)Kr0-UaB*7Y>t82EQ%!)(&(XuAYtTsYy-dz+w=$ir)VJpe!_$ z6SGpX^i(af3{o=VlFPC);|J8#(=_8#vdxDe|Cok+ANhYwbE*FO`Su2m1~w+&9<_9~ z-|tTU_ACGN`~CNW5WYYBn^B#SwZ(t4%3aPp z;o)|L6Rk569KGxFLUPx@!6OOa+5OjQLK5w&nAmwxkC5rZ|m&HT8G%GVZxB_@ME z>>{rnXUqyiJrT(8GMj_ap#yN_!9-lO5e8mR3cJiK3NE{_UM&=*vIU`YkiL$1%kf+1 z4=jk@7EEj`u(jy$HnzE33ZVW_J4bj}K;vT?T91YlO(|Y0FU4r+VdbmQ97%(J5 zkK*Bed8+C}FcZ@HIgdCMioV%A<*4pw_n}l*{Cr4}a(lq|injK#O?$tyvyE`S%(1`H z_wwRvk#13ElkZvij2MFGOj`fhy?nC^8`Zyo%yVcUAfEr8x&J#A{|moUBAV_^f$hpaUuyQeY3da^ zS9iRgf87YBwfe}>BO+T&Fl%rfpZh#+AM?Dq-k$Bq`vG6G_b4z%Kbd&v>qFjow*mBl z-OylnqOpLg}or7_VNwRg2za3VBK6FUfFX{|TD z`Wt0Vm2H$vdlRWYQJqDmM?JUbVqL*ZQY|5&sY*?!&%P8qhA~5+Af<{MaGo(dl&C5t zE%t!J0 zh6jqANt4ABdPxSTrVV}fLsRQal*)l&_*rFq(Ez}ClEH6LHv{J#v?+H-BZ2)Wy{K@9 z+ovXHq~DiDvm>O~r$LJo!cOuwL+Oa--6;UFE2q@g3N8Qkw5E>ytz^(&($!O47+i~$ zKM+tkAd-RbmP{s_rh+ugTD;lriL~`Xwkad#;_aM?nQ7L_muEFI}U_4$phjvYgleK~`Fo`;GiC07&Hq1F<%p;9Q;tv5b?*QnR%8DYJH3P>Svmv47Y>*LPZJy8_{9H`g6kQpyZU{oJ`m%&p~D=K#KpfoJ@ zn-3cqmHsdtN!f?~w+(t+I`*7GQA#EQC^lUA9(i6=i1PqSAc|ha91I%X&nXzjYaM{8$s&wEx@aVkQ6M{E2 zfzId#&r(XwUNtPcq4Ngze^+XaJA1EK-%&C9j>^9(secqe{}z>hR5CFNveMsVA)m#S zk)_%SidkY-XmMWlVnQ(mNJ>)ooszQ#vaK;!rPmGKXV7am^_F!Lz>;~{VrIO$;!#30XRhE1QqO_~#+Ux;B_D{Nk=grn z8Y0oR^4RqtcYM)7a%@B(XdbZCOqnX#fD{BQTeLvRHd(irHKq=4*jq34`6@VAQR8WG z^%)@5CXnD_T#f%@-l${>y$tfb>2LPmc{~5A82|16mH)R?&r#KKLs7xpN-D`=&Cm^R zvMA6#Ahr<3X>Q7|-qfTY)}32HkAz$_mibYV!I)u>bmjK`qwBe(>za^0Kt*HnFbSdO z1>+ryKCNxmm^)*$XfiDOF2|{-v3KKB?&!(S_Y=Ht@|ir^hLd978xuI&N{k>?(*f8H z=ClxVJK_%_z1TH0eUwm2J+2To7FK4o+n_na)&#VLn1m;!+CX+~WC+qg1?PA~KdOlC zW)C@pw75_xoe=w7i|r9KGIvQ$+3K?L{7TGHwrQM{dCp=Z*D}3kX7E-@sZnup!BImw z*T#a=+WcTwL78exTgBn|iNE3#EsOorO z*kt)gDzHiPt07fmisA2LWN?AymkdqTgr?=loT7z@d`wnlr6oN}@o|&JX!yPzC*Y8d zu6kWlTzE1)ckyBn+0Y^HMN+GA$wUO_LN6W>mxCo!0?oiQvT`z$jbSEu&{UHRU0E8# z%B^wOc@S!yhMT49Y)ww(Xta^8pmPCe@eI5C*ed96)AX9<>))nKx0(sci8gwob_1}4 z0DIL&vsJ1_s%<@y%U*-eX z5rN&(zef-5G~?@r79oZGW1d!WaTqQn0F6RIOa9tJ=0(kdd{d1{<*tHT#cCvl*i>YY zH+L7jq8xZNcTUBqj(S)ztTU!TM!RQ}In*n&Gn<>(60G7}4%WQL!o>hbJqNDSGwl#H z`4k+twp0cj%PsS+NKaxslAEu9!#U3xT1|_KB6`h=PI0SW`P9GTa7caD1}vKEglV8# zjKZR`pluCW19c2fM&ZG)c3T3Um;ir3y(tSCJ7Agl6|b524dy5El{^EQBG?E61H0XY z`bqg!;zhGhyMFl&(o=JWEJ8n~z)xI}A@C0d2hQGvw7nGv)?POU@(kS1m=%`|+^ika zXl8zjS?xqW$WlO?Ewa;vF~XbybHBor$f<%I&*t$F5fynwZlTGj|IjZtVfGa7l&tK} zW>I<69w(cZLu)QIVG|M2xzW@S+70NinQzk&Y0+3WT*cC)rx~04O-^<{JohU_&HL5XdUKW!uFy|i$FB|EMu0eUyW;gsf`XfIc!Z0V zeK&*hPL}f_cX=@iv>K%S5kL;cl_$v?n(Q9f_cChk8Lq$glT|=e+T*8O4H2n<=NGmn z+2*h+v;kBvF>}&0RDS>)B{1!_*XuE8A$Y=G8w^qGMtfudDBsD5>T5SB;Qo}fSkkiV ze^K^M(UthkwrD!&*tTsu>Dacdj_q`~V%r_twr$(Ct&_dKeeXE?fA&4&yASJWJ*}~- zel=@W)tusynfC_YqH4ll>4Eg`Xjs5F7Tj>tTLz<0N3)X<1px_d2yUY>X~y>>93*$) z5PuNMQLf9Bu?AAGO~a_|J2akO1M*@VYN^VxvP0F$2>;Zb9;d5Yfd8P%oFCCoZE$ z4#N$^J8rxYjUE_6{T%Y>MmWfHgScpuGv59#4u6fpTF%~KB^Ae`t1TD_^Ud#DhL+Dm zbY^VAM#MrAmFj{3-BpVSWph2b_Y6gCnCAombVa|1S@DU)2r9W<> zT5L8BB^er3zxKt1v(y&OYk!^aoQisqU zH(g@_o)D~BufUXcPt!Ydom)e|aW{XiMnes2z&rE?og>7|G+tp7&^;q?Qz5S5^yd$i z8lWr4g5nctBHtigX%0%XzIAB8U|T6&JsC4&^hZBw^*aIcuNO47de?|pGXJ4t}BB`L^d8tD`H`i zqrP8?#J@8T#;{^B!KO6J=@OWKhAerih(phML`(Rg7N1XWf1TN>=Z3Do{l_!d~DND&)O)D>ta20}@Lt77qSnVsA7>)uZAaT9bsB>u&aUQl+7GiY2|dAEg@%Al3i316y;&IhQL^8fw_nwS>f60M_-m+!5)S_6EPM7Y)(Nq^8gL7(3 zOiot`6Wy6%vw~a_H?1hLVzIT^i1;HedHgW9-P#)}Y6vF%C=P70X0Tk^z9Te@kPILI z_(gk!k+0%CG)%!WnBjjw*kAKs_lf#=5HXC00s-}oM-Q1aXYLj)(1d!_a7 z*Gg4Fe6F$*ujVjI|79Z5+Pr`us%zW@ln++2l+0hsngv<{mJ%?OfSo_3HJXOCys{Ug z00*YR-(fv<=&%Q!j%b-_ppA$JsTm^_L4x`$k{VpfLI(FMCap%LFAyq;#ns5bR7V+x zO!o;c5y~DyBPqdVQX)8G^G&jWkBy2|oWTw>)?5u}SAsI$RjT#)lTV&Rf8;>u*qXnb z8F%Xb=7#$m)83z%`E;49)t3fHInhtc#kx4wSLLms!*~Z$V?bTyUGiS&m>1P(952(H zuHdv=;o*{;5#X-uAyon`hP}d#U{uDlV?W?_5UjJvf%11hKwe&(&9_~{W)*y1nR5f_ z!N(R74nNK`y8>B!0Bt_Vr!;nc3W>~RiKtGSBkNlsR#-t^&;$W#)f9tTlZz>n*+Fjz z3zXZ;jf(sTM(oDzJt4FJS*8c&;PLTW(IQDFs_5QPy+7yhi1syPCarvqrHFcf&yTy)^O<1EBx;Ir`5W{TIM>{8w&PB>ro4;YD<5LF^TjTb0!zAP|QijA+1Vg>{Afv^% zmrkc4o6rvBI;Q8rj4*=AZacy*n8B{&G3VJc)so4$XUoie0)vr;qzPZVbb<#Fc=j+8CGBWe$n|3K& z_@%?{l|TzKSlUEO{U{{%Fz_pVDxs7i9H#bnbCw7@4DR=}r_qV!Zo~CvD4ZI*+j3kO zW6_=|S`)(*gM0Z;;}nj`73OigF4p6_NPZQ-Od~e$c_);;4-7sR>+2u$6m$Gf%T{aq zle>e3(*Rt(TPD}03n5)!Ca8Pu!V}m6v0o1;5<1h$*|7z|^(3$Y&;KHKTT}hV056wuF0Xo@mK-52~r=6^SI1NC%c~CC?n>yX6wPTgiWYVz!Sx^atLby9YNn1Rk{g?|pJaxD4|9cUf|V1_I*w zzxK)hRh9%zOl=*$?XUjly5z8?jPMy%vEN)f%T*|WO|bp5NWv@B(K3D6LMl!-6dQg0 zXNE&O>Oyf%K@`ngCvbGPR>HRg5!1IV$_}m@3dWB7x3t&KFyOJn9pxRXCAzFr&%37wXG;z^xaO$ekR=LJG ztIHpY8F5xBP{mtQidqNRoz= z@){+N3(VO5bD+VrmS^YjG@+JO{EOIW)9=F4v_$Ed8rZtHvjpiEp{r^c4F6Ic#ChlC zJX^DtSK+v(YdCW)^EFcs=XP7S>Y!4=xgmv>{S$~@h=xW-G4FF9?I@zYN$e5oF9g$# zb!eVU#J+NjLyX;yb)%SY)xJdvGhsnE*JEkuOVo^k5PyS=o#vq!KD46UTW_%R=Y&0G zFj6bV{`Y6)YoKgqnir2&+sl+i6foAn-**Zd1{_;Zb7Ki=u394C5J{l^H@XN`_6XTKY%X1AgQM6KycJ+= zYO=&t#5oSKB^pYhNdzPgH~aEGW2=ec1O#s-KG z71}LOg@4UEFtp3GY1PBemXpNs6UK-ax*)#$J^pC_me;Z$Je(OqLoh|ZrW*mAMBFn< zHttjwC&fkVfMnQeen8`Rvy^$pNRFVaiEN4Pih*Y3@jo!T0nsClN)pdrr9AYLcZxZ| zJ5Wlj+4q~($hbtuY zVQ7hl>4-+@6g1i`1a)rvtp-;b0>^`Dloy(#{z~ytgv=j4q^Kl}wD>K_Y!l~ zp(_&7sh`vfO(1*MO!B%<6E_bx1)&s+Ae`O)a|X=J9y~XDa@UB`m)`tSG4AUhoM=5& znWoHlA-(z@3n0=l{E)R-p8sB9XkV zZ#D8wietfHL?J5X0%&fGg@MH~(rNS2`GHS4xTo7L$>TPme+Is~!|79=^}QbPF>m%J zFMkGzSndiPO|E~hrhCeo@&Ea{M(ieIgRWMf)E}qeTxT8Q#g-!Lu*x$v8W^M^>?-g= zwMJ$dThI|~M06rG$Sv@C@tWR>_YgaG&!BAbkGggVQa#KdtDB)lMLNVLN|51C@F^y8 zCRvMB^{GO@j=cHfmy}_pCGbP%xb{pNN>? z?7tBz$1^zVaP|uaatYaIN+#xEN4jBzwZ|YI_)p(4CUAz1ZEbDk>J~Y|63SZaak~#0 zoYKruYsWHoOlC1(MhTnsdUOwQfz5p6-D0}4;DO$B;7#M{3lSE^jnTT;ns`>!G%i*F?@pR1JO{QTuD0U+~SlZxcc8~>IB{)@8p`P&+nDxNj`*gh|u?yrv$phpQcW)Us)bi`kT%qLj(fi{dWRZ%Es2!=3mI~UxiW0$-v3vUl?#g{p6eF zMEUAqo5-L0Ar(s{VlR9g=j7+lt!gP!UN2ICMokAZ5(Agd>})#gkA2w|5+<%-CuEP# zqgcM}u@3(QIC^Gx<2dbLj?cFSws_f3e%f4jeR?4M^M3cx1f+Qr6ydQ>n)kz1s##2w zk}UyQc+Z5G-d-1}{WzjkLXgS-2P7auWSJ%pSnD|Uivj5u!xk0 z_^-N9r9o;(rFDt~q1PvE#iJZ_f>J3gcP$)SOqhE~pD2|$=GvpL^d!r z6u=sp-CrMoF7;)}Zd7XO4XihC4ji?>V&(t^?@3Q&t9Mx=qex6C9d%{FE6dvU6%d94 zIE;hJ1J)cCqjv?F``7I*6bc#X)JW2b4f$L^>j{*$R`%5VHFi*+Q$2;nyieduE}qdS{L8y8F08yLs?w}{>8>$3236T-VMh@B zq-nujsb_1aUv_7g#)*rf9h%sFj*^mIcImRV*k~Vmw;%;YH(&ylYpy!&UjUVqqtfG` zox3esju?`unJJA_zKXRJP)rA3nXc$m^{S&-p|v|-0x9LHJm;XIww7C#R$?00l&Yyj z=e}gKUOpsImwW?N)+E(awoF@HyP^EhL+GlNB#k?R<2>95hz!h9sF@U20DHSB3~WMa zk90+858r@-+vWwkawJ)8ougd(i#1m3GLN{iSTylYz$brAsP%=&m$mQQrH$g%3-^VR zE%B`Vi&m8f3T~&myTEK28BDWCVzfWir1I?03;pX))|kY5ClO^+bae z*7E?g=3g7EiisYOrE+lA)2?Ln6q2*HLNpZEWMB|O-JI_oaHZB%CvYB(%=tU= zE*OY%QY58fW#RG5=gm0NR#iMB=EuNF@)%oZJ}nmm=tsJ?eGjia{e{yuU0l3{d^D@)kVDt=1PE)&tf_hHC%0MB znL|CRCPC}SeuVTdf>-QV70`0(EHizc21s^sU>y%hW0t!0&y<7}Wi-wGy>m%(-jsDj zP?mF|>p_K>liZ6ZP(w5(|9Ga%>tLgb$|doDDfkdW>Z z`)>V2XC?NJT26mL^@ zf+IKr27TfM!UbZ@?zRddC7#6ss1sw%CXJ4FWC+t3lHZupzM77m^=9 z&(a?-LxIq}*nvv)y?27lZ{j zifdl9hyJudyP2LpU$-kXctshbJDKS{WfulP5Dk~xU4Le4c#h^(YjJit4#R8_khheS z|8(>2ibaHES4+J|DBM7I#QF5u-*EdN{n=Kt@4Zt?@Tv{JZA{`4 zU#kYOv{#A&gGPwT+$Ud}AXlK3K7hYzo$(fBSFjrP{QQ zeaKg--L&jh$9N}`pu{Bs>?eDFPaWY4|9|foN%}i;3%;@4{dc+iw>m}{3rELqH21G! z`8@;w-zsJ1H(N3%|1B@#ioLOjib)j`EiJqPQVSbPSPVHCj6t5J&(NcWzBrzCiDt{4 zdlPAUKldz%6x5II1H_+jv)(xVL+a;P+-1hv_pM>gMRr%04@k;DTokASSKKhU1Qms| zrWh3a!b(J3n0>-tipg{a?UaKsP7?+|@A+1WPDiQIW1Sf@qDU~M_P65_s}7(gjTn0X zucyEm)o;f8UyshMy&>^SC3I|C6jR*R_GFwGranWZe*I>K+0k}pBuET&M~ z;Odo*ZcT?ZpduHyrf8E%IBFtv;JQ!N_m>!sV6ly$_1D{(&nO~w)G~Y`7sD3#hQk%^ zp}ucDF_$!6DAz*PM8yE(&~;%|=+h(Rn-=1Wykas_-@d&z#=S}rDf`4w(rVlcF&lF! z=1)M3YVz7orwk^BXhslJ8jR);sh^knJW(Qmm(QdSgIAIdlN4Te5KJisifjr?eB{FjAX1a0AB>d?qY4Wx>BZ8&}5K0fA+d{l8 z?^s&l8#j7pR&ijD?0b%;lL9l$P_mi2^*_OL+b}4kuLR$GAf85sOo02?Y#90}CCDiS zZ%rbCw>=H~CBO=C_JVV=xgDe%b4FaEFtuS7Q1##y686r%F6I)s-~2(}PWK|Z8M+Gu zl$y~5@#0Ka%$M<&Cv%L`a8X^@tY&T7<0|(6dNT=EsRe0%kp1Qyq!^43VAKYnr*A5~ zsI%lK1ewqO;0TpLrT9v}!@vJK{QoVa_+N4FYT#h?Y8rS1S&-G+m$FNMP?(8N`MZP zels(*?kK{{^g9DOzkuZXJ2;SrOQsp9T$hwRB1(phw1c7`!Q!by?Q#YsSM#I12RhU{$Q+{xj83axHcftEc$mNJ8_T7A-BQc*k(sZ+~NsO~xAA zxnbb%dam_fZlHvW7fKXrB~F&jS<4FD2FqY?VG?ix*r~MDXCE^WQ|W|WM;gsIA4lQP zJ2hAK@CF*3*VqPr2eeg6GzWFlICi8S>nO>5HvWzyZTE)hlkdC_>pBej*>o0EOHR|) z$?};&I4+_?wvL*g#PJ9)!bc#9BJu1(*RdNEn>#Oxta(VWeM40ola<0aOe2kSS~{^P zDJBd}0L-P#O-CzX*%+$#v;(x%<*SPgAje=F{Zh-@ucd2DA(yC|N_|ocs*|-!H%wEw z@Q!>siv2W;C^^j^59OAX03&}&D*W4EjCvfi(ygcL#~t8XGa#|NPO+*M@Y-)ctFA@I z-p7npT1#5zOLo>7q?aZpCZ=iecn3QYklP;gF0bq@>oyBq94f6C=;Csw3PkZ|5q=(c zfs`aw?II0e(h=|7o&T+hq&m$; zBrE09Twxd9BJ2P+QPN}*OdZ-JZV7%av@OM7v!!NL8R;%WFq*?{9T3{ct@2EKgc8h) zMxoM$SaF#p<`65BwIDfmXG6+OiK0e)`I=!A3E`+K@61f}0e z!2a*FOaDrOe>U`q%K!QN`&=&0C~)CaL3R4VY(NDt{Xz(Xpqru5=r#uQN1L$Je1*dkdqQ*=lofQaN%lO!<5z9ZlHgxt|`THd>2 zsWfU$9=p;yLyJyM^t zS2w9w?Bpto`@H^xJpZDKR1@~^30Il6oFGfk5%g6w*C+VM)+%R@gfIwNprOV5{F^M2 zO?n3DEzpT+EoSV-%OdvZvNF+pDd-ZVZ&d8 zKeIyrrfPN=EcFRCPEDCVflX#3-)Ik_HCkL(ejmY8vzcf-MTA{oHk!R2*36`O68$7J zf}zJC+bbQk--9Xm!u#lgLvx8TXx2J258E5^*IZ(FXMpq$2LUUvhWQPs((z1+2{Op% z?J}9k5^N=z;7ja~zi8a_-exIqWUBJwohe#4QJ`|FF*$C{lM18z^#hX6!5B8KAkLUX ziP=oti-gpV(BsLD{0(3*dw}4JxK23Y7M{BeFPucw!sHpY&l%Ws4pSm`+~V7;bZ%Dx zeI)MK=4vC&5#;2MT7fS?^ch9?2;%<8Jlu-IB&N~gg8t;6S-#C@!NU{`p7M8@2iGc& zg|JPg%@gCoCQ&s6JvDU&`X2S<57f(k8nJ1wvBu{8r?;q3_kpZZ${?|( z+^)UvR33sjSd)aT!UPkA;ylO6{aE3MQa{g%Mcf$1KONcjO@&g5zPHWtzM1rYC{_K> zgQNcs<{&X{OA=cEWw5JGqpr0O>x*Tfak2PE9?FuWtz^DDNI}rwAaT0(bdo-<+SJ6A z&}S%boGMWIS0L}=S>|-#kRX;e^sUsotry(MjE|3_9duvfc|nwF#NHuM-w7ZU!5ei8 z6Mkf>2)WunY2eU@C-Uj-A zG(z0Tz2YoBk>zCz_9-)4a>T46$(~kF+Y{#sA9MWH%5z#zNoz)sdXq7ZR_+`RZ%0(q zC7&GyS_|BGHNFl8Xa%@>iWh%Gr?=J5<(!OEjauj5jyrA-QXBjn0OAhJJ9+v=!LK`` z@g(`^*84Q4jcDL`OA&ZV60djgwG`|bcD*i50O}Q{9_noRg|~?dj%VtKOnyRs$Uzqg z191aWoR^rDX#@iSq0n z?9Sg$WSRPqSeI<}&n1T3!6%Wj@5iw5`*`Btni~G=&;J+4`7g#OQTa>u`{4ZZ(c@s$ zK0y;ySOGD-UTjREKbru{QaS>HjN<2)R%Nn-TZiQ(Twe4p@-saNa3~p{?^V9Nixz@a zykPv~<@lu6-Ng9i$Lrk(xi2Tri3q=RW`BJYOPC;S0Yly%77c727Yj-d1vF!Fuk{Xh z)lMbA69y7*5ufET>P*gXQrxsW+ zz)*MbHZv*eJPEXYE<6g6_M7N%#%mR{#awV3i^PafNv(zyI)&bH?F}2s8_rR(6%!V4SOWlup`TKAb@ee>!9JKPM=&8g#BeYRH9FpFybxBXQI2|g}FGJfJ+ zY-*2hB?o{TVL;Wt_ek;AP5PBqfDR4@Z->_182W z{P@Mc27j6jE*9xG{R$>6_;i=y{qf(c`5w9fa*`rEzX6t!KJ(p1H|>J1pC-2zqWENF zmm=Z5B4u{cY2XYl(PfrInB*~WGWik3@1oRhiMOS|D;acnf-Bs(QCm#wR;@Vf!hOPJ zgjhDCfDj$HcyVLJ=AaTbQ{@vIv14LWWF$=i-BDoC11}V;2V8A`S>_x)vIq44-VB-v z*w-d}$G+Ql?En8j!~ZkCpQ$|cA0|+rrY>tiCeWxkRGPoarxlGU2?7%k#F693RHT24 z-?JsiXlT2PTqZqNb&sSc>$d;O4V@|b6VKSWQb~bUaWn1Cf0+K%`Q&Wc<>mQ>*iEGB zbZ;aYOotBZ{vH3y<0A*L0QVM|#rf*LIsGx(O*-7)r@yyBIzJnBFSKBUSl1e|8lxU* zzFL+YDVVkIuzFWeJ8AbgN&w(4-7zbiaMn{5!JQXu)SELk*CNL+Fro|2v|YO)1l15t zs(0^&EB6DPMyaqvY>=KL>)tEpsn;N5Q#yJj<9}ImL((SqErWN3Q=;tBO~ExTCs9hB z2E$7eN#5wX4<3m^5pdjm#5o>s#eS_Q^P)tm$@SawTqF*1dj_i#)3};JslbLKHXl_N z)Fxzf>FN)EK&Rz&*|6&%Hs-^f{V|+_vL1S;-1K-l$5xiC@}%uDuwHYhmsV?YcOUlk zOYkG5v2+`+UWqpn0aaaqrD3lYdh0*!L`3FAsNKu=Q!vJu?Yc8n|CoYyDo_`r0mPoo z8>XCo$W4>l(==h?2~PoRR*kEe)&IH{1sM41mO#-36`02m#nTX{r*r`Q5rZ2-sE|nA zhnn5T#s#v`52T5|?GNS`%HgS2;R(*|^egNPDzzH_z^W)-Q98~$#YAe)cEZ%vge965AS_am#DK#pjPRr-!^za8>`kksCAUj(Xr*1NW5~e zpypt_eJpD&4_bl_y?G%>^L}=>xAaV>KR6;^aBytqpiHe%!j;&MzI_>Sx7O%F%D*8s zSN}cS^<{iiK)=Ji`FpO#^zY!_|D)qeRNAtgmH)m;qC|mq^j(|hL`7uBz+ULUj37gj zksdbnU+LSVo35riSX_4z{UX=%n&}7s0{WuZYoSfwAP`8aKN9P@%e=~1`~1ASL-z%# zw>DO&ixr}c9%4InGc*_y42bdEk)ZdG7-mTu0bD@_vGAr*NcFoMW;@r?@LUhRI zCUJgHb`O?M3!w)|CPu~ej%fddw20lod?Ufp8Dmt0PbnA0J%KE^2~AIcnKP()025V> zG>noSM3$5Btmc$GZoyP^v1@Poz0FD(6YSTH@aD0}BXva?LphAiSz9f&Y(aDAzBnUh z?d2m``~{z;{}kZJ>a^wYI?ry(V9hIoh;|EFc0*-#*`$T0DRQ1;WsqInG;YPS+I4{g zJGpKk%%Sdc5xBa$Q^_I~(F97eqDO7AN3EN0u)PNBAb+n+ zWBTxQx^;O9o0`=g+Zrt_{lP!sgWZHW?8bLYS$;1a@&7w9rD9|Ge;Gb?sEjFoF9-6v z#!2)t{DMHZ2@0W*fCx;62d#;jouz`R5Y(t{BT=$N4yr^^o$ON8d{PQ=!O zX17^CrdM~7D-;ZrC!||<+FEOxI_WI3CA<35va%4v>gc zEX-@h8esj=a4szW7x{0g$hwoWRQG$yK{@3mqd-jYiVofJE!Wok1* znV7Gm&Ssq#hFuvj1sRyHg(6PFA5U*Q8Rx>-blOs=lb`qa{zFy&n4xY;sd$fE+<3EI z##W$P9M{B3c3Si9gw^jlPU-JqD~Cye;wr=XkV7BSv#6}DrsXWFJ3eUNrc%7{=^sP> zrp)BWKA9<}^R9g!0q7yWlh;gr_TEOD|#BmGq<@IV;ueg+D2}cjpp+dPf&Q(36sFU&K8}hA85U61faW&{ zlB`9HUl-WWCG|<1XANN3JVAkRYvr5U4q6;!G*MTdSUt*Mi=z_y3B1A9j-@aK{lNvx zK%p23>M&=KTCgR!Ee8c?DAO2_R?B zkaqr6^BSP!8dHXxj%N1l+V$_%vzHjqvu7p@%Nl6;>y*S}M!B=pz=aqUV#`;h%M0rU zHfcog>kv3UZAEB*g7Er@t6CF8kHDmKTjO@rejA^ULqn!`LwrEwOVmHx^;g|5PHm#B zZ+jjWgjJ!043F+&#_;D*mz%Q60=L9Ove|$gU&~As5^uz@2-BfQ!bW)Khn}G+Wyjw- z19qI#oB(RSNydn0t~;tAmK!P-d{b-@@E5|cdgOS#!>%#Rj6ynkMvaW@37E>@hJP^8 z2zk8VXx|>#R^JCcWdBCy{0nPmYFOxN55#^-rlqobe0#L6)bi?E?SPymF*a5oDDeSd zO0gx?#KMoOd&G(2O@*W)HgX6y_aa6iMCl^~`{@UR`nMQE`>n_{_aY5nA}vqU8mt8H z`oa=g0SyiLd~BxAj2~l$zRSDHxvDs;I4>+M$W`HbJ|g&P+$!U7-PHX4RAcR0szJ*( ze-417=bO2q{492SWrqDK+L3#ChUHtz*@MP)e^%@>_&#Yk^1|tv@j4%3T)diEX zATx4K*hcO`sY$jk#jN5WD<=C3nvuVsRh||qDHnc~;Kf59zr0;c7VkVSUPD%NnnJC_ zl3F^#f_rDu8l}l8qcAz0FFa)EAt32IUy_JLIhU_J^l~FRH&6-ivSpG2PRqzDdMWft>Zc(c)#tb%wgmWN%>IOPm zZi-noqS!^Ftb81pRcQi`X#UhWK70hy4tGW1mz|+vI8c*h@ zfFGJtW3r>qV>1Z0r|L>7I3un^gcep$AAWfZHRvB|E*kktY$qQP_$YG60C@X~tTQjB3%@`uz!qxtxF+LE!+=nrS^07hn` zEgAp!h|r03h7B!$#OZW#ACD+M;-5J!W+{h|6I;5cNnE(Y863%1(oH}_FTW})8zYb$7czP zg~Szk1+_NTm6SJ0MS_|oSz%e(S~P-&SFp;!k?uFayytV$8HPwuyELSXOs^27XvK-D zOx-Dl!P|28DK6iX>p#Yb%3`A&CG0X2S43FjN%IB}q(!hC$fG}yl1y9W&W&I@KTg6@ zK^kpH8=yFuP+vI^+59|3%Zqnb5lTDAykf z9S#X`3N(X^SpdMyWQGOQRjhiwlj!0W-yD<3aEj^&X%=?`6lCy~?`&WSWt z?U~EKFcCG_RJ(Qp7j=$I%H8t)Z@6VjA#>1f@EYiS8MRHZphp zMA_5`znM=pzUpBPO)pXGYpQ6gkine{6u_o!P@Q+NKJ}k!_X7u|qfpAyIJb$_#3@wJ z<1SE2Edkfk9C!0t%}8Yio09^F`YGzpaJHGk*-ffsn85@)%4@`;Fv^8q(-Wk7r=Q8p zT&hD`5(f?M{gfzGbbwh8(}G#|#fDuk7v1W)5H9wkorE0ZZjL0Q1=NRGY>zwgfm81DdoaVwNH;or{{eSyybt)m<=zXoA^RALYG-2t zouH|L*BLvmm9cdMmn+KGopyR@4*=&0&4g|FLoreZOhRmh=)R0bg~ zT2(8V_q7~42-zvb)+y959OAv!V$u(O3)%Es0M@CRFmG{5sovIq4%8Ahjk#*5w{+)+ zMWQoJI_r$HxL5km1#6(e@{lK3Udc~n0@g`g$s?VrnQJ$!oPnb?IHh-1qA`Rz$)Ai< z6w$-MJW-gKNvOhL+XMbE7&mFt`x1KY>k4(!KbbpZ`>`K@1J<(#vVbjx@Z@(6Q}MF# zMnbr-f55(cTa^q4+#)=s+ThMaV~E`B8V=|W_fZWDwiso8tNMTNse)RNBGi=gVwgg% zbOg8>mbRN%7^Um-7oj4=6`$|(K7!+t^90a{$18Z>}<#!bm%ZEFQ{X(yBZMc>lCz0f1I2w9Sq zuGh<9<=AO&g6BZte6hn>Qmvv;Rt)*cJfTr2=~EnGD8P$v3R|&1RCl&7)b+`=QGapi zPbLg_pxm`+HZurtFZ;wZ=`Vk*do~$wB zxoW&=j0OTbQ=Q%S8XJ%~qoa3Ea|au5o}_(P;=!y-AjFrERh%8la!z6Fn@lR?^E~H12D?8#ht=1F;7@o4$Q8GDj;sSC%Jfn01xgL&%F2 zwG1|5ikb^qHv&9hT8w83+yv&BQXOQyMVJSBL(Ky~p)gU3#%|blG?IR9rP^zUbs7rOA0X52Ao=GRt@C&zlyjNLv-} z9?*x{y(`509qhCV*B47f2hLrGl^<@SuRGR!KwHei?!CM10Tq*YDIoBNyRuO*>3FU? zHjipIE#B~y3FSfOsMfj~F9PNr*H?0oHyYB^G(YyNh{SxcE(Y-`x5jFMKb~HO*m+R% zrq|ic4fzJ#USpTm;X7K+E%xsT_3VHKe?*uc4-FsILUH;kL>_okY(w`VU*8+l>o>Jm ziU#?2^`>arnsl#)*R&nf_%>A+qwl%o{l(u)M?DK1^mf260_oteV3#E_>6Y4!_hhVD zM8AI6MM2V*^_M^sQ0dmHu11fy^kOqXqzpr?K$`}BKWG`=Es(9&S@K@)ZjA{lj3ea7_MBP zk(|hBFRjHVMN!sNUkrB;(cTP)T97M$0Dtc&UXSec<+q?y>5=)}S~{Z@ua;1xt@=T5 zI7{`Z=z_X*no8s>mY;>BvEXK%b`a6(DTS6t&b!vf_z#HM{Uoy_5fiB(zpkF{})ruka$iX*~pq1ZxD?q68dIo zIZSVls9kFGsTwvr4{T_LidcWtt$u{kJlW7moRaH6+A5hW&;;2O#$oKyEN8kx`LmG)Wfq4ykh+q{I3|RfVpkR&QH_x;t41Uw z`P+tft^E2B$domKT@|nNW`EHwyj>&}K;eDpe z1bNOh=fvIfk`&B61+S8ND<(KC%>y&?>opCnY*r5M+!UrWKxv0_QvTlJc>X#AaI^xo zaRXL}t5Ej_Z$y*|w*$6D+A?Lw-CO-$itm^{2Ct82-<0IW)0KMNvJHgBrdsIR0v~=H z?n6^}l{D``Me90`^o|q!olsF?UX3YSq^6Vu>Ijm>>PaZI8G@<^NGw{Cx&%|PwYrfw zR!gX_%AR=L3BFsf8LxI|K^J}deh0ZdV?$3r--FEX`#INxsOG6_=!v)DI>0q|BxT)z z-G6kzA01M?rba+G_mwNMQD1mbVbNTWmBi*{s_v_Ft9m2Avg!^78(QFu&n6mbRJ2bA zv!b;%yo{g*9l2)>tsZJOOp}U~8VUH`}$ z8p_}t*XIOehezolNa-a2x0BS})Y9}&*TPgua{Ewn-=wVrmJUeU39EKx+%w%=ixQWK zDLpwaNJs65#6o7Ln7~~X+p_o2BR1g~VCfxLzxA{HlWAI6^H;`juI=&r1jQrUv_q0Z z1Ja-tjdktrrP>GOC*#p?*xfQU5MqjMsBe!9lh(u8)w$e@Z|>aUHI5o;MGw*|Myiz3 z-f0;pHg~Q#%*Kx8MxH%AluVXjG2C$)WL-K63@Q`#y9_k_+}eR(x4~dp7oV-ek0H>I zgy8p#i4GN{>#v=pFYUQT(g&b$OeTy-X_#FDgNF8XyfGY6R!>inYn8IR2RDa&O!(6< znXs{W!bkP|s_YI*Yx%4stI`=ZO45IK6rBs`g7sP40ic}GZ58s?Mc$&i`kq_tfci>N zIHrC0H+Qpam1bNa=(`SRKjixBTtm&e`j9porEci!zdlg1RI0Jw#b(_Tb@RQK1Zxr_ z%7SUeH6=TrXt3J@js`4iDD0=IoHhK~I7^W8^Rcp~Yaf>2wVe|Hh1bUpX9ATD#moByY57-f2Ef1TP^lBi&p5_s7WGG9|0T}dlfxOx zXvScJO1Cnq`c`~{Dp;{;l<-KkCDE+pmexJkd}zCgE{eF=)K``-qC~IT6GcRog_)!X z?fK^F8UDz$(zFUrwuR$qro5>qqn>+Z%<5>;_*3pZ8QM|yv9CAtrAx;($>4l^_$_-L z*&?(77!-=zvnCVW&kUcZMb6;2!83si518Y%R*A3JZ8Is|kUCMu`!vxDgaWjs7^0j( ziTaS4HhQ)ldR=r)_7vYFUr%THE}cPF{0H45FJ5MQW^+W>P+eEX2kLp3zzFe*-pFVA zdDZRybv?H|>`9f$AKVjFWJ=wegO7hOOIYCtd?Vj{EYLT*^gl35|HQ`R=ti+ADm{jyQE7K@kdjuqJhWVSks>b^ zxha88-h3s;%3_5b1TqFCPTxVjvuB5U>v=HyZ$?JSk+&I%)M7KE*wOg<)1-Iy)8-K! z^XpIt|0ibmk9RtMmlUd7#Ap3Q!q9N4atQy)TmrhrFhfx1DAN`^vq@Q_SRl|V z#lU<~n67$mT)NvHh`%als+G-)x1`Y%4Bp*6Un5Ri9h=_Db zA-AdP!f>f0m@~>7X#uBM?diI@)Egjuz@jXKvm zJo+==juc9_<;CqeRaU9_Mz@;3e=E4=6TK+c`|uu#pIqhSyNm`G(X)&)B`8q0RBv#> z`gGlw(Q=1Xmf55VHj%C#^1lpc>LY8kfA@|rlC1EA<1#`iuyNO z(=;irt{_&K=i4)^x%;U(Xv<)+o=dczC5H3W~+e|f~{*ucxj@{Yi-cw^MqYr3fN zF5D+~!wd$#al?UfMnz(@K#wn`_5na@rRr8XqN@&M&FGEC@`+OEv}sI1hw>Up0qAWf zL#e4~&oM;TVfjRE+10B_gFlLEP9?Q-dARr3xi6nQqnw>k-S;~b z;!0s2VS4}W8b&pGuK=7im+t(`nz@FnT#VD|!)eQNp-W6)@>aA+j~K*H{$G`y2|QHY z|Hmy+CR@#jWY4~)lr1qBJB_RfHJFfP<}pK5(#ZZGSqcpyS&}01LnTWk5fzmXMGHkJ zTP6L^B+uj;lmB_W<~4=${+v0>z31M!-_O@o-O9GyW)j_mjx}!0@br_LE-7SIuPP84 z;5=O(U*g_um0tyG|61N@d9lEuOeiRd+#NY^{nd5;-CVlw&Ap7J?qwM^?E29wvS}2d zbzar4Fz&RSR(-|s!Z6+za&Z zY#D<5q_JUktIzvL0)yq_kLWG6DO{ri=?c!y!f(Dk%G{8)k`Gym%j#!OgXVDD3;$&v@qy#ISJfp=Vm>pls@9-mapVQChAHHd-x+OGx)(*Yr zC1qDUTZ6mM(b_hi!TuFF2k#8uI2;kD70AQ&di$L*4P*Y-@p`jdm%_c3f)XhYD^6M8&#Y$ZpzQMcR|6nsH>b=*R_Von!$BTRj7yGCXokoAQ z&ANvx0-Epw`QIEPgI(^cS2f(Y85yV@ygI{ewyv5Frng)e}KCZF7JbR(&W618_dcEh(#+^zZFY;o<815<5sOHQdeax9_!PyM&;{P zkBa5xymca0#)c#tke@3KNEM8a_mT&1gm;p&&JlMGH(cL(b)BckgMQ^9&vRwj!~3@l zY?L5}=Jzr080OGKb|y`ee(+`flQg|!lo6>=H)X4`$Gz~hLmu2a%kYW_Uu8x09Pa0J zKZ`E$BKJ=2GPj_3l*TEcZ*uYRr<*J^#5pILTT;k_cgto1ZL-%slyc16J~OH-(RgDA z%;EjEnoUkZ&acS{Q8`{i6T5^nywgqQI5bDIymoa7CSZG|WWVk>GM9)zy*bNih|QIm z%0+(Nnc*a_xo;$=!HQYaapLms>J1ToyjtFByY`C2H1wT#178#4+|{H0BBqtCdd$L% z_3Hc60j@{t9~MjM@LBalR&6@>B;9?r<7J~F+WXyYu*y3?px*=8MAK@EA+jRX8{CG?GI-< z54?Dc9CAh>QTAvyOEm0^+x;r2BWX|{3$Y7)L5l*qVE*y0`7J>l2wCmW zL1?|a`pJ-l{fb_N;R(Z9UMiSj6pQjOvQ^%DvhIJF!+Th7jO2~1f1N+(-TyCFYQZYw z4)>7caf^Ki_KJ^Zx2JUb z&$3zJy!*+rCV4%jqwyuNY3j1ZEiltS0xTzd+=itTb;IPYpaf?8Y+RSdVdpacB(bVQ zC(JupLfFp8y43%PMj2}T|VS@%LVp>hv4Y!RPMF?pp8U_$xCJ)S zQx!69>bphNTIb9yn*_yfj{N%bY)t{L1cs8<8|!f$;UQ*}IN=2<6lA;x^(`8t?;+ST zh)z4qeYYgZkIy{$4x28O-pugO&gauRh3;lti9)9Pvw+^)0!h~%m&8Q!AKX%urEMnl z?yEz?g#ODn$UM`+Q#$Q!6|zsq_`dLO5YK-6bJM6ya>}H+vnW^h?o$z;V&wvuM$dR& zeEq;uUUh$XR`TWeC$$c&Jjau2it3#%J-y}Qm>nW*s?En?R&6w@sDXMEr#8~$=b(gk zwDC3)NtAP;M2BW_lL^5ShpK$D%@|BnD{=!Tq)o(5@z3i7Z){} zGr}Exom_qDO{kAVkZ*MbLNHE666Kina#D{&>Jy%~w7yX$oj;cYCd^p9zy z8*+wgSEcj$4{WxKmCF(5o7U4jqwEvO&dm1H#7z}%VXAbW&W24v-tS6N3}qrm1OnE)fUkoE8yMMn9S$?IswS88tQWm4#Oid#ckgr6 zRtHm!mfNl-`d>O*1~d7%;~n+{Rph6BBy^95zqI{K((E!iFQ+h*C3EsbxNo_aRm5gj zKYug($r*Q#W9`p%Bf{bi6;IY0v`pB^^qu)gbg9QHQ7 zWBj(a1YSu)~2RK8Pi#C>{DMlrqFb9e_RehEHyI{n?e3vL_}L>kYJC z_ly$$)zFi*SFyNrnOt(B*7E$??s67EO%DgoZL2XNk8iVx~X_)o++4oaK1M|ou73vA0K^503j@uuVmLcHH4ya-kOIDfM%5%(E z+Xpt~#7y2!KB&)PoyCA+$~DXqxPxxALy!g-O?<9+9KTk4Pgq4AIdUkl`1<1#j^cJg zgU3`0hkHj_jxV>`Y~%LAZl^3o0}`Sm@iw7kwff{M%VwtN)|~!p{AsfA6vB5UolF~d zHWS%*uBDt<9y!9v2Xe|au&1j&iR1HXCdyCjxSgG*L{wmTD4(NQ=mFjpa~xooc6kju z`~+d{j7$h-;HAB04H!Zscu^hZffL#9!p$)9>sRI|Yovm)g@F>ZnosF2EgkU3ln0bR zTA}|+E(tt)!SG)-bEJi_0m{l+(cAz^pi}`9=~n?y&;2eG;d9{M6nj>BHGn(KA2n|O zt}$=FPq!j`p&kQ8>cirSzkU0c08%8{^Qyqi-w2LoO8)^E7;;I1;HQ6B$u0nNaX2CY zSmfi)F`m94zL8>#zu;8|{aBui@RzRKBlP1&mfFxEC@%cjl?NBs`cr^nm){>;$g?rhKr$AO&6qV_Wbn^}5tfFBry^e1`%du2~o zs$~dN;S_#%iwwA_QvmMjh%Qo?0?rR~6liyN5Xmej8(*V9ym*T`xAhHih-v$7U}8=dfXi2i*aAB!xM(Xekg*ix@r|ymDw*{*s0?dlVys2e)z62u1 z+k3esbJE=-P5S$&KdFp+2H7_2e=}OKDrf( z9-207?6$@f4m4B+9E*e((Y89!q?zH|mz_vM>kp*HGXldO0Hg#!EtFhRuOm$u8e~a9 z5(roy7m$Kh+zjW6@zw{&20u?1f2uP&boD}$#Zy)4o&T;vyBoqFiF2t;*g=|1=)PxB z8eM3Mp=l_obbc?I^xyLz?4Y1YDWPa+nm;O<$Cn;@ane616`J9OO2r=rZr{I_Kizyc zP#^^WCdIEp*()rRT+*YZK>V@^Zs=ht32x>Kwe zab)@ZEffz;VM4{XA6e421^h~`ji5r%)B{wZu#hD}f3$y@L0JV9f3g{-RK!A?vBUA}${YF(vO4)@`6f1 z-A|}e#LN{)(eXloDnX4Vs7eH|<@{r#LodP@Nz--$Dg_Par%DCpu2>2jUnqy~|J?eZ zBG4FVsz_A+ibdwv>mLp>P!(t}E>$JGaK$R~;fb{O3($y1ssQQo|5M;^JqC?7qe|hg zu0ZOqeFcp?qVn&Qu7FQJ4hcFi&|nR!*j)MF#b}QO^lN%5)4p*D^H+B){n8%VPUzi! zDihoGcP71a6!ab`l^hK&*dYrVYzJ0)#}xVrp!e;lI!+x+bfCN0KXwUAPU9@#l7@0& QuEJmfE|#`Dqx|px0L@K;Y5)KL literal 0 HcmV?d00001 diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/java/okhttp-gson-nextgen/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..ffed3a254e9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/gradlew b/samples/client/petstore/java/okhttp-gson-nextgen/gradlew new file mode 100644 index 00000000000..005bcde0428 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original 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 POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${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='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# 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 ;; #( + MSYS* | 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" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/gradlew.bat b/samples/client/petstore/java/okhttp-gson-nextgen/gradlew.bat new file mode 100644 index 00000000000..6a68175eb70 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/hello.txt b/samples/client/petstore/java/okhttp-gson-nextgen/hello.txt new file mode 100644 index 00000000000..6769dd60bdf --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/hello.txt @@ -0,0 +1 @@ +Hello world! \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/pom.xml b/samples/client/petstore/java/okhttp-gson-nextgen/pom.xml new file mode 100644 index 00000000000..931f95599d3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/pom.xml @@ -0,0 +1,349 @@ + + 4.0.0 + org.openapitools + petstore-okhttp-gson-nextgen + jar + petstore-okhttp-gson-nextgen + 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-compiler-plugin + 3.8.1 + + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M5 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 10 + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.0 + + + + test-jar + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.2.0 + + + 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-javadoc-plugin + 3.3.1 + + + attach-javadocs + + jar + + + + + none + + + http.response.details + a + Http Response Details: + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.2.0 + + + attach-sources + + jar-no-fork + + + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + + + + + .gitignore + + + + + + true + 4 + + + + + + + + + + 1.8 + + true + + + + + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.0.1 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + io.swagger + swagger-annotations + ${swagger-core-version} + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + com.squareup.okhttp3 + okhttp + ${okhttp-version} + + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + io.gsonfire + gson-fire + ${gson-fire-version} + + + org.apache.oltu.oauth2 + org.apache.oltu.oauth2.client + 1.0.1 + + + org.apache.commons + commons-lang3 + ${commons-lang3-version} + + + org.threeten + threetenbp + ${threetenbp-version} + + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation-version} + provided + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + javax.ws.rs + jsr311-api + 1.1.1 + + + javax.ws.rs + javax.ws.rs-api + 2.0 + + + + junit + junit + ${junit-version} + test + + + org.mockito + mockito-core + 3.12.4 + test + + + + 1.8 + ${java.version} + ${java.version} + 1.8.5 + 1.6.3 + 4.9.2 + 2.8.8 + 3.12.0 + 0.2.1 + 1.5.0 + 1.3.5 + 4.13.2 + UTF-8 + 2.17.3 + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/settings.gradle b/samples/client/petstore/java/okhttp-gson-nextgen/settings.gradle new file mode 100644 index 00000000000..db500510c40 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "petstore-okhttp-gson-nextgen" \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/AndroidManifest.xml b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..54fbcb3da1e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiCallback.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiCallback.java new file mode 100644 index 00000000000..e9ab7a8d7a6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiCallback.java @@ -0,0 +1,62 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API download processing. + * + * @param bytesRead bytes Read + * @param contentLength content length of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 00000000000..7e3cf65e18c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,1552 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.*; +import okhttp3.internal.http.HttpMethod; +import okhttp3.internal.tls.OkHostnameVerifier; +import okhttp3.logging.HttpLoggingInterceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.format.DateTimeFormatter; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.common.message.types.GrantType; + +import javax.net.ssl.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; +import java.net.URI; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.text.DateFormat; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; +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; +import org.openapitools.client.auth.OAuth; +import org.openapitools.client.auth.RetryingOAuth; +import org.openapitools.client.auth.OAuthFlow; + +/** + *

    ApiClient class.

    + */ +public class ApiClient { + + private String basePath = "http://petstore.swagger.io:80/v2"; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private Map defaultCookieMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + private KeyManager[] keyManagers; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /** + * Basic constructor for ApiClient + */ + public ApiClient() { + init(); + initHttpClient(); + + // Setup authentications (key: authentication name, value: authentication). + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("api_key_query", new ApiKeyAuth("query", "api_key_query")); + authentications.put("bearer_test", new HttpBearerAuth("bearer")); + authentications.put("http_basic_test", new HttpBasicAuth()); + authentications.put("http_signature_test", new HttpBearerAuth("signature")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Basic constructor with custom OkHttpClient + * + * @param client a {@link okhttp3.OkHttpClient} object + */ + public ApiClient(OkHttpClient client) { + init(); + + httpClient = client; + + // Setup authentications (key: authentication name, value: authentication). + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("api_key_query", new ApiKeyAuth("query", "api_key_query")); + authentications.put("bearer_test", new HttpBearerAuth("bearer")); + authentications.put("http_basic_test", new HttpBasicAuth()); + authentications.put("http_signature_test", new HttpBearerAuth("signature")); + authentications.put("petstore_auth", new OAuth()); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID + * + * @param clientId client ID + */ + public ApiClient(String clientId) { + this(clientId, null, null); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID and additional parameters + * + * @param clientId client ID + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, Map parameters) { + this(clientId, null, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with client ID, secret, and additional parameters + * + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String clientId, String clientSecret, Map parameters) { + this(null, clientId, clientSecret, parameters); + } + + /** + * Constructor for ApiClient to support access token retry on 401/403 configured with base path, client ID, secret, and additional parameters + * + * @param basePath base path + * @param clientId client ID + * @param clientSecret client secret + * @param parameters a {@link java.util.Map} of parameters + */ + public ApiClient(String basePath, String clientId, String clientSecret, Map parameters) { + init(); + if (basePath != null) { + this.basePath = basePath; + } + + String tokenUrl = ""; + if (!"".equals(tokenUrl) && !URI.create(tokenUrl).isAbsolute()) { + URI uri = URI.create(getBasePath()); + tokenUrl = uri.getScheme() + ":" + + (uri.getAuthority() != null ? "//" + uri.getAuthority() : "") + + tokenUrl; + if (!URI.create(tokenUrl).isAbsolute()) { + throw new IllegalArgumentException("OAuth2 token URL must be an absolute URL"); + } + } + RetryingOAuth retryingOAuth = new RetryingOAuth(tokenUrl, clientId, OAuthFlow.implicit, clientSecret, parameters); + authentications.put( + "petstore_auth", + retryingOAuth + ); + initHttpClient(Collections.singletonList(retryingOAuth)); + // Setup authentications (key: authentication name, value: authentication). + authentications.put("api_key", new ApiKeyAuth("header", "api_key")); + authentications.put("api_key_query", new ApiKeyAuth("query", "api_key_query")); + authentications.put("bearer_test", new HttpBearerAuth("bearer")); + authentications.put("http_basic_test", new HttpBasicAuth()); + authentications.put("http_signature_test", new HttpBearerAuth("signature")); + + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + private void initHttpClient() { + initHttpClient(Collections.emptyList()); + } + + private void initHttpClient(List interceptors) { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.addNetworkInterceptor(getProgressInterceptor()); + for (Interceptor interceptor: interceptors) { + builder.addInterceptor(interceptor); + } + + httpClient = builder.build(); + } + + private void init() { + verifyingSsl = true; + + json = new JSON(); + + // Set default User-Agent. + setUserAgent("OpenAPI-Generator/1.0.0/java"); + + authentications = new HashMap(); + } + + /** + * Get base path + * + * @return Base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://petstore.swagger.io:80/v2 + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client, which must never be null. + * + * @param newHttpClient An instance of OkHttpClient + * @return Api Client + * @throws java.lang.NullPointerException when newHttpClient is null + */ + public ApiClient setHttpClient(OkHttpClient newHttpClient) { + this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + /** + *

    Getter for the field keyManagers.

    + * + * @return an array of {@link javax.net.ssl.KeyManager} objects + */ + public KeyManager[] getKeyManagers() { + return keyManagers; + } + + /** + * Configure client keys to use for authorization in an SSL session. + * Use null to reset to default. + * + * @param managers The KeyManagers to use + * @return ApiClient + */ + public ApiClient setKeyManagers(KeyManager[] managers) { + this.keyManagers = managers; + applySslSettings(); + return this; + } + + /** + *

    Getter for the field dateFormat.

    + * + * @return a {@link java.text.DateFormat} object + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + *

    Setter for the field dateFormat.

    + * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.json.setDateFormat(dateFormat); + return this; + } + + /** + *

    Set SqlDateFormat.

    + * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setSqlDateFormat(DateFormat dateFormat) { + this.json.setSqlDateFormat(dateFormat); + return this; + } + + /** + *

    Set OffsetDateTimeFormat.

    + * + * @param dateFormat a {@link org.threeten.bp.format.DateTimeFormatter} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + this.json.setOffsetDateTimeFormat(dateFormat); + return this; + } + + /** + *

    Set LocalDateFormat.

    + * + * @param dateFormat a {@link org.threeten.bp.format.DateTimeFormatter} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + this.json.setLocalDateFormat(dateFormat); + return this; + } + + /** + *

    Set LenientOnJson.

    + * + * @param lenientOnJson a boolean + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setLenientOnJson(boolean lenientOnJson) { + this.json.setLenientOnJson(lenientOnJson); + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof OAuth) { + ((OAuth) auth).setAccessToken(accessToken); + return; + } + } + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + 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 ApiClient + */ + 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 enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); + } else { + final OkHttpClient.Builder builder = httpClient.newBuilder(); + builder.interceptors().remove(loggingInterceptor); + httpClient = builder.build(); + loggingInterceptor = null; + } + } + this.debugging = 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 temporary folder. + * + * @see
    createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the temporary folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.connectTimeoutMillis(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get read timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getReadTimeout() { + return httpClient.readTimeoutMillis(); + } + + /** + * Sets the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param readTimeout read timeout in milliseconds + * @return Api client + */ + public ApiClient setReadTimeout(int readTimeout) { + httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get write timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getWriteTimeout() { + return httpClient.writeTimeoutMillis(); + } + + /** + * Sets the write timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param writeTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setWriteTimeout(int writeTimeout) { + httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * + * @return Token request builder + */ + public TokenRequestBuilder getTokenEndPoint() { + for (Authentication apiAuth : authentications.values()) { + if (apiAuth instanceof RetryingOAuth) { + RetryingOAuth retryingOAuth = (RetryingOAuth) apiAuth; + return retryingOAuth.getTokenRequestBuilder(); + } + } + return null; + } + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { + //Serialize to json string and remove the " enclosing characters + String jsonStr = json.serialize(param); + return jsonStr.substring(1, jsonStr.length() - 1); + } 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); + } + } + + /** + * Formats the specified query parameter to a list containing a single {@code Pair} object. + * + * Note that {@code value} must not be a collection. + * + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list containing a single {@code Pair} object. + */ + public List parameterToPair(String name, Object value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value instanceof Collection) { + return params; + } + + params.add(new Pair(name, parameterToString(value))); + return params; + } + + /** + * Formats the specified collection query parameters to a list of {@code Pair} objects. + * + * Note that the values of each of the returned Pair objects are percent-encoded. + * + * @param collectionFormat The collection format of the parameter. + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list of {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Collection value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { + return params; + } + + // create the params based on the collection format + if ("multi".equals(collectionFormat)) { + for (Object item : value) { + params.add(new Pair(name, escapeString(parameterToString(item)))); + } + return params; + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + // escape all delimiters except commas, which are URI reserved + // characters + if ("ssv".equals(collectionFormat)) { + delimiter = escapeString(" "); + } else if ("tsv".equals(collectionFormat)) { + delimiter = escapeString("\t"); + } else if ("pipes".equals(collectionFormat)) { + delimiter = escapeString("|"); + } + + StringBuilder sb = new StringBuilder(); + for (Object item : value) { + sb.append(delimiter); + sb.append(escapeString(parameterToString(item))); + } + + params.add(new Pair(name, sb.substring(delimiter.length()))); + + return params; + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param value The value of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(String collectionFormat, Collection value) { + // create the value based on the collection format + if ("multi".equals(collectionFormat)) { + // not valid for path params + return parameterToString(value); + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + if ("ssv".equals(collectionFormat)) { + delimiter = " "; + } else if ("tsv".equals(collectionFormat)) { + delimiter = "\t"; + } else if ("pipes".equals(collectionFormat)) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : value) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + return sb.substring(delimiter.length()); + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * 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 (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + 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, + * returns null. If it matches "any", JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return null; + } + + if (contentTypes[0].equals("*/*")) { + 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 to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws org.openapitools.client.ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return json.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws org.openapitools.client.ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = json.serialize(obj); + } else { + content = null; + } + return RequestBody.create(content, MediaType.parse(contentType)); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws org.openapitools.client.ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @return Prepared file for the download + * @throws java.io.IOException If fail to prepare file for download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("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 = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + 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); + } + // Files.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return Files.createTempFile(prefix, suffix).toFile(); + else + return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @return ApiResponse<T> + * @throws org.openapitools.client.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws org.openapitools.client.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + * @see #execute(Call, Type) + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Call call, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } catch (Exception e) { + callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @return Type + * @throws org.openapitools.client.ApiException If the response has an unsuccessful status code or + * fail to deserialize the response body + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + if (response.body() != null) { + try { + response.body().close(); + } catch (Exception e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP call + * @throws org.openapitools.client.ApiException If fail to serialize the request body object + */ + public Call buildCall(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + + return httpClient.newCall(request); + } + + /** + * Build an HTTP request with the given options. + * + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP request + * @throws org.openapitools.client.ApiException If fail to serialize the request body object + */ + public Request buildRequest(String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams + List allQueryParams = new ArrayList(queryParams); + allQueryParams.addAll(collectionQueryParams); + + final String url = buildUrl(path, queryParams, collectionQueryParams); + + // prepare HTTP request body + RequestBody reqBody; + String contentType = headerParams.get("Content-Type"); + + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentType)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentType)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create("", MediaType.parse(contentType)); + } + } else { + reqBody = serialize(body, contentType); + } + + // update parameters with authentication settings + updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); + + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + processCookieParams(cookieParams, reqBuilder); + + // Associate callback with request (if not null) so interceptor can + // access it when creating ProgressResponseBody + reqBuilder.tag(callback); + + Request request = null; + + if (callback != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return request; + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param path The sub path + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @return The full URL + */ + public String buildUrl(String path, List queryParams, List collectionQueryParams) { + final StringBuilder url = new StringBuilder(); + url.append(basePath).append(path); + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { + String prefix = url.toString().contains("?") ? "&" : "?"; + for (Pair param : collectionQueryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + // collection query parameter value already escaped as part of parameterToPairs + url.append(escapeString(param.getName())).append("=").append(value); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Set cookie parameters to the request builder, including default cookies. + * + * @param cookieParams Cookie parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { + for (Entry param : cookieParams.entrySet()) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + for (Entry param : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(param.getKey())) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + } + } + + /** + * 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 payload HTTP request body + * @param method HTTP method + * @param uri URI + */ + public 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) { + throw new RuntimeException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); + } else { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + param.getKey() + "\""); + mpBuilder.addPart(partHeaders, RequestBody.create(parameterToString(param.getValue()), null)); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Get network interceptor to add it to the httpClient to track download progress for + * async requests. + */ + private Interceptor getProgressInterceptor() { + return new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + final Request request = chain.request(); + final Response originalResponse = chain.proceed(request); + if (request.tag() instanceof ApiCallback) { + final ApiCallback callback = (ApiCallback) request.tag(); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), callback)) + .build(); + } + return originalResponse; + } + }; + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + TrustManager[] trustManagers; + HostnameVerifier hostnameVerifier; + if (!verifyingSsl) { + trustManagers = new TrustManager[]{ + new X509TrustManager() { + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[]{}; + } + } + }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + } else { + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + if (sslCaCert == null) { + trustManagerFactory.init((KeyStore) null); + } else { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + Integer.toString(index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + trustManagerFactory.init(caKeyStore); + } + trustManagers = trustManagerFactory.getTrustManagers(); + hostnameVerifier = OkHostnameVerifier.INSTANCE; + } + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient = httpClient.newBuilder() + .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) + .hostnameVerifier(hostnameVerifier) + .build(); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /** + * Convert the HTTP request body to a string. + * + * @param request The HTTP request object + * @return The string representation of the HTTP request body + * @throws org.openapitools.client.ApiException If fail to serialize the request body object into a string + */ + private String requestBodyToString(RequestBody requestBody) throws ApiException { + if (requestBody != null) { + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return buffer.readUtf8(); + } catch (final IOException e) { + throw new ApiException(e); + } + } + + // empty http request body + return ""; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiException.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiException.java new file mode 100644 index 00000000000..5851f0405ad --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiException.java @@ -0,0 +1,154 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Map; +import java.util.List; + +/** + *

    ApiException class.

    + */ +@SuppressWarnings("serial") +@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; + + /** + *

    Constructor for ApiException.

    + */ + public ApiException() {} + + /** + *

    Constructor for ApiException.

    + * + * @param throwable a {@link java.lang.Throwable} object + */ + public ApiException(Throwable throwable) { + super(throwable); + } + + /** + *

    Constructor for ApiException.

    + * + * @param message the error message + */ + public ApiException(String message) { + super(message); + } + + /** + *

    Constructor for ApiException.

    + * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + *

    Constructor for ApiException.

    + * + * @param message the error message + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

    Constructor for ApiException.

    + * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + /** + *

    Constructor for ApiException.

    + * + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, Map> responseHeaders, String responseBody) { + this((String) null, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

    Constructor for ApiException.

    + * + * @param code HTTP status code + * @param message a {@link java.lang.String} object + */ + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + /** + *

    Constructor for ApiException.

    + * + * @param code HTTP status code + * @param message the error message + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + 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/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiResponse.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiResponse.java new file mode 100644 index 00000000000..fb13945bd77 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ApiResponse.java @@ -0,0 +1,76 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + *

    Constructor for ApiResponse.

    + * + * @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); + } + + /** + *

    Constructor for ApiResponse.

    + * + * @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 the status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + *

    Get the headers.

    + * + * @return a {@link java.util.Map} of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + *

    Get the data.

    + * + * @return the data + */ + public T getData() { + return data; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/Configuration.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/Configuration.java new file mode 100644 index 00000000000..476456fd4ed --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/Configuration.java @@ -0,0 +1,39 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@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/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/GzipRequestInterceptor.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/GzipRequestInterceptor.java new file mode 100644 index 00000000000..63442a34f40 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/GzipRequestInterceptor.java @@ -0,0 +1,85 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; + +import java.io.IOException; + +/** + * Encodes request bodies using gzip. + * + * Taken from https://github.com/square/okhttp/issues/350 + */ +class GzipRequestInterceptor implements Interceptor { + @Override + public Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { + return chain.proceed(originalRequest); + } + + Request compressedRequest = originalRequest.newBuilder() + .header("Content-Encoding", "gzip") + .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) + .build(); + return chain.proceed(compressedRequest); + } + + private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return new RequestBody() { + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() { + return buffer.size(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + sink.write(buffer.snapshot()); + } + }; + } + + private RequestBody gzip(final RequestBody body) { + return new RequestBody() { + @Override + public MediaType contentType() { + return body.contentType(); + } + + @Override + public long contentLength() { + return -1; // We don't know the compressed length in advance! + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); + body.writeTo(gzipSink); + gzipSink.close(); + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java new file mode 100644 index 00000000000..53717e8ac51 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java @@ -0,0 +1,594 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; +import io.gsonfire.TypeSelector; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.format.DateTimeFormatter; + +import okio.ByteString; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.ParsePosition; +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.HashMap; + +/* + * A JSON utility class + * + * NOTE: in the future, this class may be converted to static, which may break + * backward-compatibility + */ +public class JSON { + private Gson gson; + private boolean isLenientOnJson = false; + private DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + private OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); + private LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + private ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); + + @SuppressWarnings("unchecked") + public static GsonBuilder createGson() { + GsonFireBuilder fireBuilder = new GsonFireBuilder() + .registerTypeSelector(org.openapitools.client.model.Animal.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("Cat", org.openapitools.client.model.Cat.class); + classByDiscriminatorValue.put("Dog", org.openapitools.client.model.Dog.class); + classByDiscriminatorValue.put("Animal", org.openapitools.client.model.Animal.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }) + .registerTypeSelector(org.openapitools.client.model.Cat.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("Cat", org.openapitools.client.model.Cat.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }) + .registerTypeSelector(org.openapitools.client.model.Dog.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("Dog", org.openapitools.client.model.Dog.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }) + .registerTypeSelector(org.openapitools.client.model.GrandparentAnimal.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("ParentPet", org.openapitools.client.model.ParentPet.class); + classByDiscriminatorValue.put("GrandparentAnimal", org.openapitools.client.model.GrandparentAnimal.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "pet_type")); + } + }) + .registerTypeSelector(org.openapitools.client.model.Mammal.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("Pig", org.openapitools.client.model.Pig.class); + classByDiscriminatorValue.put("whale", org.openapitools.client.model.Whale.class); + classByDiscriminatorValue.put("zebra", org.openapitools.client.model.Zebra.class); + classByDiscriminatorValue.put("mammal", org.openapitools.client.model.Mammal.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }) + .registerTypeSelector(org.openapitools.client.model.NullableShape.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("Quadrilateral", org.openapitools.client.model.Quadrilateral.class); + classByDiscriminatorValue.put("Triangle", org.openapitools.client.model.Triangle.class); + classByDiscriminatorValue.put("NullableShape", org.openapitools.client.model.NullableShape.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "shapeType")); + } + }) + .registerTypeSelector(org.openapitools.client.model.ParentPet.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("ParentPet", org.openapitools.client.model.ParentPet.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "pet_type")); + } + }) + .registerTypeSelector(org.openapitools.client.model.Pig.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("BasquePig", org.openapitools.client.model.BasquePig.class); + classByDiscriminatorValue.put("DanishPig", org.openapitools.client.model.DanishPig.class); + classByDiscriminatorValue.put("Pig", org.openapitools.client.model.Pig.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "className")); + } + }) + .registerTypeSelector(org.openapitools.client.model.Quadrilateral.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("ComplexQuadrilateral", org.openapitools.client.model.ComplexQuadrilateral.class); + classByDiscriminatorValue.put("SimpleQuadrilateral", org.openapitools.client.model.SimpleQuadrilateral.class); + classByDiscriminatorValue.put("Quadrilateral", org.openapitools.client.model.Quadrilateral.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "quadrilateralType")); + } + }) + .registerTypeSelector(org.openapitools.client.model.Shape.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("Quadrilateral", org.openapitools.client.model.Quadrilateral.class); + classByDiscriminatorValue.put("Triangle", org.openapitools.client.model.Triangle.class); + classByDiscriminatorValue.put("Shape", org.openapitools.client.model.Shape.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "shapeType")); + } + }) + .registerTypeSelector(org.openapitools.client.model.ShapeOrNull.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("Quadrilateral", org.openapitools.client.model.Quadrilateral.class); + classByDiscriminatorValue.put("Triangle", org.openapitools.client.model.Triangle.class); + classByDiscriminatorValue.put("ShapeOrNull", org.openapitools.client.model.ShapeOrNull.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "shapeType")); + } + }) + .registerTypeSelector(org.openapitools.client.model.Triangle.class, new TypeSelector() { + @Override + public Class getClassForElement(JsonElement readElement) { + Map classByDiscriminatorValue = new HashMap(); + classByDiscriminatorValue.put("EquilateralTriangle", org.openapitools.client.model.EquilateralTriangle.class); + classByDiscriminatorValue.put("IsoscelesTriangle", org.openapitools.client.model.IsoscelesTriangle.class); + classByDiscriminatorValue.put("ScaleneTriangle", org.openapitools.client.model.ScaleneTriangle.class); + classByDiscriminatorValue.put("Triangle", org.openapitools.client.model.Triangle.class); + return getClassByDiscriminator(classByDiscriminatorValue, + getDiscriminatorValue(readElement, "triangleType")); + } + }) + ; + GsonBuilder builder = fireBuilder.createGsonBuilder(); + return builder; + } + + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if (null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + /** + * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. + * + * @param classByDiscriminatorValue The map of discriminator values to Java classes. + * @param discriminatorValue The value of the OpenAPI discriminator in the input data. + * @return The Java class that implements the OpenAPI schema + */ + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); + if (null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + + public JSON() { + gson = createGson() + .registerTypeAdapter(Date.class, dateTypeAdapter) + .registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter) + .registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter) + .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) + .registerTypeAdapter(byte[].class, byteArrayAdapter) + .registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesClass.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Animal.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Apple.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.AppleReq.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfArrayOfNumberOnly.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfNumberOnly.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ArrayTest.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Banana.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.BananaReq.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.BasquePig.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Capitalization.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Cat.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.CatAllOf.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Category.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ClassModel.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Client.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ComplexQuadrilateral.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.DanishPig.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.DeprecatedObject.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Dog.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.DogAllOf.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Drawing.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.EnumArrays.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.EnumTest.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.EquilateralTriangle.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.FileSchemaTestClass.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Foo.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.FormatTest.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Fruit.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.FruitReq.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.GmFruit.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.GrandparentAnimal.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.HasOnlyReadOnly.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.HealthCheckResult.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.InlineResponseDefault.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.IsoscelesTriangle.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Mammal.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.MapTest.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.MixedPropertiesAndAdditionalPropertiesClass.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Model200Response.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ModelApiResponse.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ModelReturn.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Name.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.NullableClass.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.NullableShape.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.NumberOnly.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ObjectWithDeprecatedFields.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Order.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.OuterComposite.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ParentPet.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Pet.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Pig.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Quadrilateral.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.QuadrilateralInterface.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ReadOnlyFirst.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ScaleneTriangle.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Shape.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ShapeInterface.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.ShapeOrNull.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.SimpleQuadrilateral.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.SpecialModelName.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Tag.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Triangle.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.TriangleInterface.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.User.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Whale.CustomTypeAdapterFactory()) + .registerTypeAdapterFactory(new org.openapitools.client.model.Zebra.CustomTypeAdapterFactory()) + .create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public void setGson(Gson gson) { + this.gson = gson; + } + + public void setLenientOnJson(boolean lenientOnJson) { + isLenientOnJson = lenientOnJson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public T deserialize(String body, Type returnType) { + try { + if (isLenientOnJson) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw (e); + } + } + } + + /** + * Gson TypeAdapter for Byte Array type + */ + public class ByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(ByteString.of(value).base64()); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); + } + } + } + + /** + * Gson TypeAdapter for JSR310 OffsetDateTime type + */ + public class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public OffsetDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + + public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + return OffsetDateTime.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDate type + */ + public class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } + } + + public void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + offsetDateTimeTypeAdapter.setFormat(dateFormat); + } + + public void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + + /** + * Gson TypeAdapter for java.sql.Date type + * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used + * (more efficient than SimpleDateFormat). + */ + public class SqlDateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public SqlDateTypeAdapter() {} + + public SqlDateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, java.sql.Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = date.toString(); + } + out.value(value); + } + } + + @Override + public java.sql.Date read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return new java.sql.Date(dateFormat.parse(date).getTime()); + } + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } + } + + /** + * Gson TypeAdapter for java.util.Date type + * If the dateFormat is null, ISO8601Utils will be used. + */ + public class DateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public DateTypeAdapter() {} + + public DateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = ISO8601Utils.format(date, true); + } + out.value(value); + } + } + + @Override + public Date read(JsonReader in) throws IOException { + try { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return dateFormat.parse(date); + } + return ISO8601Utils.parse(date, new ParsePosition(0)); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } catch (IllegalArgumentException e) { + throw new JsonParseException(e); + } + } + } + + public void setDateFormat(DateFormat dateFormat) { + dateTypeAdapter.setFormat(dateFormat); + } + + public void setSqlDateFormat(DateFormat dateFormat) { + sqlDateTypeAdapter.setFormat(dateFormat); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/Pair.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/Pair.java new file mode 100644 index 00000000000..8352d84046a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/Pair.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@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/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ProgressRequestBody.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ProgressRequestBody.java new file mode 100644 index 00000000000..924dd866897 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ProgressRequestBody.java @@ -0,0 +1,73 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + private final RequestBody requestBody; + + private final ApiCallback callback; + + public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { + this.requestBody = requestBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink bufferedSink = Okio.buffer(sink(sink)); + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ProgressResponseBody.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ProgressResponseBody.java new file mode 100644 index 00000000000..eee56669a4a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ProgressResponseBody.java @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.MediaType; +import okhttp3.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + private final ResponseBody responseBody; + private final ApiCallback callback; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { + this.responseBody = responseBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ServerConfiguration.java new file mode 100644 index 00000000000..e08da9aac7d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/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 description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new RuntimeException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replaceAll("\\{" + name + "\\}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ServerVariable.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ServerVariable.java new file mode 100644 index 00000000000..c2f13e21666 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/ServerVariable.java @@ -0,0 +1,23 @@ +package org.openapitools.client; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/StringUtil.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/StringUtil.java new file mode 100644 index 00000000000..4dc60597910 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/StringUtil.java @@ -0,0 +1,83 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

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

    + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/AnotherFakeApi.java new file mode 100644 index 00000000000..e258256633e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -0,0 +1,170 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; +import org.openapitools.client.ProgressRequestBody; +import org.openapitools.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import org.openapitools.client.model.Client; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class AnotherFakeApi { + private ApiClient localVarApiClient; + + public AnotherFakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public AnotherFakeApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + /** + * Build call for call123testSpecialTags + * @param client client model (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call call123testSpecialTagsCall(Client client, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = client; + + // create path and map variables + String localVarPath = "/another-fake/dummy"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call call123testSpecialTagsValidateBeforeCall(Client client, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'client' is set + if (client == null) { + throw new ApiException("Missing the required parameter 'client' when calling call123testSpecialTags(Async)"); + } + + + okhttp3.Call localVarCall = call123testSpecialTagsCall(client, _callback); + return localVarCall; + + } + + /** + * To test special tags + * To test special tags and operation ID starting with number + * @param client client model (required) + * @return Client + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public Client call123testSpecialTags(Client client) throws ApiException { + ApiResponse localVarResp = call123testSpecialTagsWithHttpInfo(client); + return localVarResp.getData(); + } + + /** + * To test special tags + * To test special tags and operation ID starting with number + * @param client client model (required) + * @return ApiResponse<Client> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ApiResponse call123testSpecialTagsWithHttpInfo(Client client) throws ApiException { + okhttp3.Call localVarCall = call123testSpecialTagsValidateBeforeCall(client, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * To test special tags (asynchronously) + * To test special tags and operation ID starting with number + * @param client client model (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call call123testSpecialTagsAsync(Client client, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = call123testSpecialTagsValidateBeforeCall(client, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/DefaultApi.java new file mode 100644 index 00000000000..c4e26ea2b1c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -0,0 +1,161 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; +import org.openapitools.client.ProgressRequestBody; +import org.openapitools.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import org.openapitools.client.model.InlineResponseDefault; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DefaultApi { + private ApiClient localVarApiClient; + + public DefaultApi() { + this(Configuration.getDefaultApiClient()); + } + + public DefaultApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + /** + * Build call for fooGet + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 response -
    + */ + public okhttp3.Call fooGetCall(final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/foo"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fooGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = fooGetCall(_callback); + return localVarCall; + + } + + /** + * + * + * @return InlineResponseDefault + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 response -
    + */ + public InlineResponseDefault fooGet() throws ApiException { + ApiResponse localVarResp = fooGetWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * + * + * @return ApiResponse<InlineResponseDefault> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 response -
    + */ + public ApiResponse fooGetWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = fooGetValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 response -
    + */ + public okhttp3.Call fooGetAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fooGetValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/FakeApi.java new file mode 100644 index 00000000000..3c5114fef1b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/FakeApi.java @@ -0,0 +1,2065 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; +import org.openapitools.client.ProgressRequestBody; +import org.openapitools.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.HealthCheckResult; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient localVarApiClient; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + /** + * Build call for fakeHealthGet + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 The instance started successfully -
    + */ + public okhttp3.Call fakeHealthGetCall(final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake/health"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeHealthGetValidateBeforeCall(final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = fakeHealthGetCall(_callback); + return localVarCall; + + } + + /** + * Health check endpoint + * + * @return HealthCheckResult + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 The instance started successfully -
    + */ + public HealthCheckResult fakeHealthGet() throws ApiException { + ApiResponse localVarResp = fakeHealthGetWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Health check endpoint + * + * @return ApiResponse<HealthCheckResult> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 The instance started successfully -
    + */ + public ApiResponse fakeHealthGetWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = fakeHealthGetValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Health check endpoint (asynchronously) + * + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 The instance started successfully -
    + */ + public okhttp3.Call fakeHealthGetAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeHealthGetValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeOuterBooleanSerialize + * @param body Input boolean as post body (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output boolean -
    + */ + public okhttp3.Call fakeOuterBooleanSerializeCall(Boolean body, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/fake/outer/boolean"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeOuterBooleanSerializeValidateBeforeCall(Boolean body, final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = fakeOuterBooleanSerializeCall(body, _callback); + return localVarCall; + + } + + /** + * + * Test serialization of outer boolean types + * @param body Input boolean as post body (optional) + * @return Boolean + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output boolean -
    + */ + public Boolean fakeOuterBooleanSerialize(Boolean body) throws ApiException { + ApiResponse localVarResp = fakeOuterBooleanSerializeWithHttpInfo(body); + return localVarResp.getData(); + } + + /** + * + * Test serialization of outer boolean types + * @param body Input boolean as post body (optional) + * @return ApiResponse<Boolean> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output boolean -
    + */ + public ApiResponse fakeOuterBooleanSerializeWithHttpInfo(Boolean body) throws ApiException { + okhttp3.Call localVarCall = fakeOuterBooleanSerializeValidateBeforeCall(body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test serialization of outer boolean types + * @param body Input boolean as post body (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output boolean -
    + */ + public okhttp3.Call fakeOuterBooleanSerializeAsync(Boolean body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeOuterBooleanSerializeValidateBeforeCall(body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeOuterCompositeSerialize + * @param outerComposite Input composite as post body (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output composite -
    + */ + public okhttp3.Call fakeOuterCompositeSerializeCall(OuterComposite outerComposite, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = outerComposite; + + // create path and map variables + String localVarPath = "/fake/outer/composite"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeOuterCompositeSerializeValidateBeforeCall(OuterComposite outerComposite, final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = fakeOuterCompositeSerializeCall(outerComposite, _callback); + return localVarCall; + + } + + /** + * + * Test serialization of object with outer number type + * @param outerComposite Input composite as post body (optional) + * @return OuterComposite + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output composite -
    + */ + public OuterComposite fakeOuterCompositeSerialize(OuterComposite outerComposite) throws ApiException { + ApiResponse localVarResp = fakeOuterCompositeSerializeWithHttpInfo(outerComposite); + return localVarResp.getData(); + } + + /** + * + * Test serialization of object with outer number type + * @param outerComposite Input composite as post body (optional) + * @return ApiResponse<OuterComposite> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output composite -
    + */ + public ApiResponse fakeOuterCompositeSerializeWithHttpInfo(OuterComposite outerComposite) throws ApiException { + okhttp3.Call localVarCall = fakeOuterCompositeSerializeValidateBeforeCall(outerComposite, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test serialization of object with outer number type + * @param outerComposite Input composite as post body (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output composite -
    + */ + public okhttp3.Call fakeOuterCompositeSerializeAsync(OuterComposite outerComposite, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeOuterCompositeSerializeValidateBeforeCall(outerComposite, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeOuterNumberSerialize + * @param body Input number as post body (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output number -
    + */ + public okhttp3.Call fakeOuterNumberSerializeCall(BigDecimal body, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/fake/outer/number"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeOuterNumberSerializeValidateBeforeCall(BigDecimal body, final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = fakeOuterNumberSerializeCall(body, _callback); + return localVarCall; + + } + + /** + * + * Test serialization of outer number types + * @param body Input number as post body (optional) + * @return BigDecimal + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output number -
    + */ + public BigDecimal fakeOuterNumberSerialize(BigDecimal body) throws ApiException { + ApiResponse localVarResp = fakeOuterNumberSerializeWithHttpInfo(body); + return localVarResp.getData(); + } + + /** + * + * Test serialization of outer number types + * @param body Input number as post body (optional) + * @return ApiResponse<BigDecimal> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output number -
    + */ + public ApiResponse fakeOuterNumberSerializeWithHttpInfo(BigDecimal body) throws ApiException { + okhttp3.Call localVarCall = fakeOuterNumberSerializeValidateBeforeCall(body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test serialization of outer number types + * @param body Input number as post body (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output number -
    + */ + public okhttp3.Call fakeOuterNumberSerializeAsync(BigDecimal body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeOuterNumberSerializeValidateBeforeCall(body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for fakeOuterStringSerialize + * @param body Input string as post body (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output string -
    + */ + public okhttp3.Call fakeOuterStringSerializeCall(String body, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/fake/outer/string"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "*/*" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call fakeOuterStringSerializeValidateBeforeCall(String body, final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = fakeOuterStringSerializeCall(body, _callback); + return localVarCall; + + } + + /** + * + * Test serialization of outer string types + * @param body Input string as post body (optional) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output string -
    + */ + public String fakeOuterStringSerialize(String body) throws ApiException { + ApiResponse localVarResp = fakeOuterStringSerializeWithHttpInfo(body); + return localVarResp.getData(); + } + + /** + * + * Test serialization of outer string types + * @param body Input string as post body (optional) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output string -
    + */ + public ApiResponse fakeOuterStringSerializeWithHttpInfo(String body) throws ApiException { + okhttp3.Call localVarCall = fakeOuterStringSerializeValidateBeforeCall(body, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * Test serialization of outer string types + * @param body Input string as post body (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Output string -
    + */ + public okhttp3.Call fakeOuterStringSerializeAsync(String body, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = fakeOuterStringSerializeValidateBeforeCall(body, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for getArrayOfEnums + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Got named array of enums -
    + */ + public okhttp3.Call getArrayOfEnumsCall(final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake/array-of-enums"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getArrayOfEnumsValidateBeforeCall(final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = getArrayOfEnumsCall(_callback); + return localVarCall; + + } + + /** + * Array of Enums + * + * @return List<OuterEnum> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Got named array of enums -
    + */ + public List getArrayOfEnums() throws ApiException { + ApiResponse> localVarResp = getArrayOfEnumsWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Array of Enums + * + * @return ApiResponse<List<OuterEnum>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Got named array of enums -
    + */ + public ApiResponse> getArrayOfEnumsWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = getArrayOfEnumsValidateBeforeCall(null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Array of Enums (asynchronously) + * + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Got named array of enums -
    + */ + public okhttp3.Call getArrayOfEnumsAsync(final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = getArrayOfEnumsValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for testBodyWithFileSchema + * @param fileSchemaTestClass (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public okhttp3.Call testBodyWithFileSchemaCall(FileSchemaTestClass fileSchemaTestClass, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = fileSchemaTestClass; + + // create path and map variables + String localVarPath = "/fake/body-with-file-schema"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testBodyWithFileSchemaValidateBeforeCall(FileSchemaTestClass fileSchemaTestClass, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'fileSchemaTestClass' is set + if (fileSchemaTestClass == null) { + throw new ApiException("Missing the required parameter 'fileSchemaTestClass' when calling testBodyWithFileSchema(Async)"); + } + + + okhttp3.Call localVarCall = testBodyWithFileSchemaCall(fileSchemaTestClass, _callback); + return localVarCall; + + } + + /** + * + * For this test, the body for this request much reference a schema named `File`. + * @param fileSchemaTestClass (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public void testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass) throws ApiException { + testBodyWithFileSchemaWithHttpInfo(fileSchemaTestClass); + } + + /** + * + * For this test, the body for this request much reference a schema named `File`. + * @param fileSchemaTestClass (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public ApiResponse testBodyWithFileSchemaWithHttpInfo(FileSchemaTestClass fileSchemaTestClass) throws ApiException { + okhttp3.Call localVarCall = testBodyWithFileSchemaValidateBeforeCall(fileSchemaTestClass, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * (asynchronously) + * For this test, the body for this request much reference a schema named `File`. + * @param fileSchemaTestClass (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public okhttp3.Call testBodyWithFileSchemaAsync(FileSchemaTestClass fileSchemaTestClass, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testBodyWithFileSchemaValidateBeforeCall(fileSchemaTestClass, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testBodyWithQueryParams + * @param query (required) + * @param user (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public okhttp3.Call testBodyWithQueryParamsCall(String query, User user, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = user; + + // create path and map variables + String localVarPath = "/fake/body-with-query-params"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (query != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("query", query)); + } + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testBodyWithQueryParamsValidateBeforeCall(String query, User user, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'query' is set + if (query == null) { + throw new ApiException("Missing the required parameter 'query' when calling testBodyWithQueryParams(Async)"); + } + + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling testBodyWithQueryParams(Async)"); + } + + + okhttp3.Call localVarCall = testBodyWithQueryParamsCall(query, user, _callback); + return localVarCall; + + } + + /** + * + * + * @param query (required) + * @param user (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public void testBodyWithQueryParams(String query, User user) throws ApiException { + testBodyWithQueryParamsWithHttpInfo(query, user); + } + + /** + * + * + * @param query (required) + * @param user (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public ApiResponse testBodyWithQueryParamsWithHttpInfo(String query, User user) throws ApiException { + okhttp3.Call localVarCall = testBodyWithQueryParamsValidateBeforeCall(query, user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * (asynchronously) + * + * @param query (required) + * @param user (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public okhttp3.Call testBodyWithQueryParamsAsync(String query, User user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testBodyWithQueryParamsValidateBeforeCall(query, user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testClientModel + * @param client client model (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call testClientModelCall(Client client, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = client; + + // create path and map variables + String localVarPath = "/fake"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testClientModelValidateBeforeCall(Client client, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'client' is set + if (client == null) { + throw new ApiException("Missing the required parameter 'client' when calling testClientModel(Async)"); + } + + + okhttp3.Call localVarCall = testClientModelCall(client, _callback); + return localVarCall; + + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param client client model (required) + * @return Client + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public Client testClientModel(Client client) throws ApiException { + ApiResponse localVarResp = testClientModelWithHttpInfo(client); + return localVarResp.getData(); + } + + /** + * To test \"client\" model + * To test \"client\" model + * @param client client model (required) + * @return ApiResponse<Client> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ApiResponse testClientModelWithHttpInfo(Client client) throws ApiException { + okhttp3.Call localVarCall = testClientModelValidateBeforeCall(client, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * To test \"client\" model (asynchronously) + * To test \"client\" model + * @param client client model (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call testClientModelAsync(Client client, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testClientModelValidateBeforeCall(client, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for testEndpointParameters + * @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, default to OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))) + * @param password None (optional) + * @param paramCallback None (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid username supplied -
    404 User not found -
    + */ + public okhttp3.Call testEndpointParametersCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (integer != null) { + localVarFormParams.put("integer", integer); + } + + if (int32 != null) { + localVarFormParams.put("int32", int32); + } + + if (int64 != null) { + localVarFormParams.put("int64", int64); + } + + if (number != null) { + localVarFormParams.put("number", number); + } + + if (_float != null) { + localVarFormParams.put("float", _float); + } + + if (_double != null) { + localVarFormParams.put("double", _double); + } + + if (string != null) { + localVarFormParams.put("string", string); + } + + if (patternWithoutDelimiter != null) { + localVarFormParams.put("pattern_without_delimiter", patternWithoutDelimiter); + } + + if (_byte != null) { + localVarFormParams.put("byte", _byte); + } + + if (binary != null) { + localVarFormParams.put("binary", binary); + } + + if (date != null) { + localVarFormParams.put("date", date); + } + + if (dateTime != null) { + localVarFormParams.put("dateTime", dateTime); + } + + if (password != null) { + localVarFormParams.put("password", password); + } + + if (paramCallback != null) { + localVarFormParams.put("callback", paramCallback); + } + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "http_basic_test" }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testEndpointParametersValidateBeforeCall(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'number' is set + if (number == null) { + throw new ApiException("Missing the required parameter 'number' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_double' is set + if (_double == null) { + throw new ApiException("Missing the required parameter '_double' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter 'patternWithoutDelimiter' is set + if (patternWithoutDelimiter == null) { + throw new ApiException("Missing the required parameter 'patternWithoutDelimiter' when calling testEndpointParameters(Async)"); + } + + // verify the required parameter '_byte' is set + if (_byte == null) { + throw new ApiException("Missing the required parameter '_byte' when calling testEndpointParameters(Async)"); + } + + + okhttp3.Call localVarCall = testEndpointParametersCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, _callback); + return localVarCall; + + } + + /** + * 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, default to OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))) + * @param password None (optional) + * @param paramCallback None (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid username supplied -
    404 User not found -
    + */ + public void testEndpointParameters(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { + testEndpointParametersWithHttpInfo(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + } + + /** + * 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, default to OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))) + * @param password None (optional) + * @param paramCallback None (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid username supplied -
    404 User not found -
    + */ + public ApiResponse testEndpointParametersWithHttpInfo(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback) throws ApiException { + okhttp3.Call localVarCall = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 (asynchronously) + * 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, default to OffsetDateTime.parse("2010-02-01T09:20:10.111110Z[UTC]", java.time.format.DateTimeFormatter.ISO_ZONED_DATE_TIME.withZone(java.time.ZoneId.systemDefault()))) + * @param password None (optional) + * @param paramCallback None (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid username supplied -
    404 User not found -
    + */ + public okhttp3.Call testEndpointParametersAsync(BigDecimal number, Double _double, String patternWithoutDelimiter, byte[] _byte, Integer integer, Integer int32, Long int64, Float _float, String string, File binary, LocalDate date, OffsetDateTime dateTime, String password, String paramCallback, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testEndpointParametersValidateBeforeCall(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testEnumParameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @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) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid request -
    404 Not found -
    + */ + public okhttp3.Call testEnumParametersCall(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (enumFormStringArray != null) { + localVarFormParams.put("enum_form_string_array", enumFormStringArray); + } + + if (enumFormString != null) { + localVarFormParams.put("enum_form_string", enumFormString); + } + + if (enumQueryStringArray != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "enum_query_string_array", enumQueryStringArray)); + } + + if (enumQueryString != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("enum_query_string", enumQueryString)); + } + + if (enumQueryInteger != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("enum_query_integer", enumQueryInteger)); + } + + if (enumQueryDouble != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("enum_query_double", enumQueryDouble)); + } + + if (enumHeaderStringArray != null) { + localVarHeaderParams.put("enum_header_string_array", localVarApiClient.parameterToString(enumHeaderStringArray)); + } + + if (enumHeaderString != null) { + localVarHeaderParams.put("enum_header_string", localVarApiClient.parameterToString(enumHeaderString)); + } + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testEnumParametersValidateBeforeCall(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString, final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = testEnumParametersCall(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, _callback); + return localVarCall; + + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @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) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid request -
    404 Not found -
    + */ + public void testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) throws ApiException { + testEnumParametersWithHttpInfo(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + } + + /** + * To test enum parameters + * To test enum parameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @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) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid request -
    404 Not found -
    + */ + public ApiResponse testEnumParametersWithHttpInfo(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString) throws ApiException { + okhttp3.Call localVarCall = testEnumParametersValidateBeforeCall(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * To test enum parameters (asynchronously) + * To test enum parameters + * @param enumHeaderStringArray Header parameter enum test (string array) (optional) + * @param enumHeaderString Header parameter enum test (string) (optional, default to -efg) + * @param enumQueryStringArray Query parameter enum test (string array) (optional) + * @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) + * @param enumFormString Form parameter enum test (string) (optional, default to -efg) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid request -
    404 Not found -
    + */ + public okhttp3.Call testEnumParametersAsync(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumFormStringArray, String enumFormString, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testEnumParametersValidateBeforeCall(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + private okhttp3.Call testGroupParametersCall(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (requiredStringGroup != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("required_string_group", requiredStringGroup)); + } + + if (requiredInt64Group != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("required_int64_group", requiredInt64Group)); + } + + if (stringGroup != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("string_group", stringGroup)); + } + + if (int64Group != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("int64_group", int64Group)); + } + + if (requiredBooleanGroup != null) { + localVarHeaderParams.put("required_boolean_group", localVarApiClient.parameterToString(requiredBooleanGroup)); + } + + if (booleanGroup != null) { + localVarHeaderParams.put("boolean_group", localVarApiClient.parameterToString(booleanGroup)); + } + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "bearer_test" }; + return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testGroupParametersValidateBeforeCall(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'requiredStringGroup' is set + if (requiredStringGroup == null) { + throw new ApiException("Missing the required parameter 'requiredStringGroup' when calling testGroupParameters(Async)"); + } + + // verify the required parameter 'requiredBooleanGroup' is set + if (requiredBooleanGroup == null) { + throw new ApiException("Missing the required parameter 'requiredBooleanGroup' when calling testGroupParameters(Async)"); + } + + // verify the required parameter 'requiredInt64Group' is set + if (requiredInt64Group == null) { + throw new ApiException("Missing the required parameter 'requiredInt64Group' when calling testGroupParameters(Async)"); + } + + + okhttp3.Call localVarCall = testGroupParametersCall(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, _callback); + return localVarCall; + + } + + + private ApiResponse testGroupParametersWithHttpInfo(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group) throws ApiException { + okhttp3.Call localVarCall = testGroupParametersValidateBeforeCall(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, null); + return localVarApiClient.execute(localVarCall); + } + + private okhttp3.Call testGroupParametersAsync(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group, Integer stringGroup, Boolean booleanGroup, Long int64Group, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testGroupParametersValidateBeforeCall(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + + public class APItestGroupParametersRequest { + private final Integer requiredStringGroup; + private final Boolean requiredBooleanGroup; + private final Long requiredInt64Group; + private Integer stringGroup; + private Boolean booleanGroup; + private Long int64Group; + + private APItestGroupParametersRequest(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group) { + this.requiredStringGroup = requiredStringGroup; + this.requiredBooleanGroup = requiredBooleanGroup; + this.requiredInt64Group = requiredInt64Group; + } + + /** + * Set stringGroup + * @param stringGroup String in group parameters (optional) + * @return APItestGroupParametersRequest + */ + public APItestGroupParametersRequest stringGroup(Integer stringGroup) { + this.stringGroup = stringGroup; + return this; + } + + /** + * Set booleanGroup + * @param booleanGroup Boolean in group parameters (optional) + * @return APItestGroupParametersRequest + */ + public APItestGroupParametersRequest booleanGroup(Boolean booleanGroup) { + this.booleanGroup = booleanGroup; + return this; + } + + /** + * Set int64Group + * @param int64Group Integer in group parameters (optional) + * @return APItestGroupParametersRequest + */ + public APItestGroupParametersRequest int64Group(Long int64Group) { + this.int64Group = int64Group; + return this; + } + + /** + * Build call for testGroupParameters + * @param _callback ApiCallback API callback + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    400 Someting wrong -
    + */ + public okhttp3.Call buildCall(final ApiCallback _callback) throws ApiException { + return testGroupParametersCall(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, _callback); + } + + /** + * Execute testGroupParameters request + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    400 Someting wrong -
    + */ + public void execute() throws ApiException { + testGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /** + * Execute testGroupParameters request with HTTP info returned + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    400 Someting wrong -
    + */ + public ApiResponse executeWithHttpInfo() throws ApiException { + return testGroupParametersWithHttpInfo(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group); + } + + /** + * Execute testGroupParameters request (asynchronously) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    400 Someting wrong -
    + */ + public okhttp3.Call executeAsync(final ApiCallback _callback) throws ApiException { + return testGroupParametersAsync(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, _callback); + } + } + + /** + * 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) + * @return APItestGroupParametersRequest + * @http.response.details + + + +
    Status Code Description Response Headers
    400 Someting wrong -
    + */ + public APItestGroupParametersRequest testGroupParameters(Integer requiredStringGroup, Boolean requiredBooleanGroup, Long requiredInt64Group) { + return new APItestGroupParametersRequest(requiredStringGroup, requiredBooleanGroup, requiredInt64Group); + } + /** + * Build call for testInlineAdditionalProperties + * @param requestBody request body (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call testInlineAdditionalPropertiesCall(Map requestBody, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = requestBody; + + // create path and map variables + String localVarPath = "/fake/inline-additionalProperties"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testInlineAdditionalPropertiesValidateBeforeCall(Map requestBody, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new ApiException("Missing the required parameter 'requestBody' when calling testInlineAdditionalProperties(Async)"); + } + + + okhttp3.Call localVarCall = testInlineAdditionalPropertiesCall(requestBody, _callback); + return localVarCall; + + } + + /** + * test inline additionalProperties + * + * @param requestBody request body (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public void testInlineAdditionalProperties(Map requestBody) throws ApiException { + testInlineAdditionalPropertiesWithHttpInfo(requestBody); + } + + /** + * test inline additionalProperties + * + * @param requestBody request body (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ApiResponse testInlineAdditionalPropertiesWithHttpInfo(Map requestBody) throws ApiException { + okhttp3.Call localVarCall = testInlineAdditionalPropertiesValidateBeforeCall(requestBody, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * test inline additionalProperties (asynchronously) + * + * @param requestBody request body (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call testInlineAdditionalPropertiesAsync(Map requestBody, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testInlineAdditionalPropertiesValidateBeforeCall(requestBody, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testJsonFormData + * @param param field1 (required) + * @param param2 field2 (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call testJsonFormDataCall(String param, String param2, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake/jsonFormData"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (param != null) { + localVarFormParams.put("param", param); + } + + if (param2 != null) { + localVarFormParams.put("param2", param2); + } + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testJsonFormDataValidateBeforeCall(String param, String param2, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'param' is set + if (param == null) { + throw new ApiException("Missing the required parameter 'param' when calling testJsonFormData(Async)"); + } + + // verify the required parameter 'param2' is set + if (param2 == null) { + throw new ApiException("Missing the required parameter 'param2' when calling testJsonFormData(Async)"); + } + + + okhttp3.Call localVarCall = testJsonFormDataCall(param, param2, _callback); + return localVarCall; + + } + + /** + * test json serialization of form data + * + * @param param field1 (required) + * @param param2 field2 (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public void testJsonFormData(String param, String param2) throws ApiException { + testJsonFormDataWithHttpInfo(param, param2); + } + + /** + * test json serialization of form data + * + * @param param field1 (required) + * @param param2 field2 (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ApiResponse testJsonFormDataWithHttpInfo(String param, String param2) throws ApiException { + okhttp3.Call localVarCall = testJsonFormDataValidateBeforeCall(param, param2, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * test json serialization of form data (asynchronously) + * + * @param param field1 (required) + * @param param2 field2 (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call testJsonFormDataAsync(String param, String param2, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testJsonFormDataValidateBeforeCall(param, param2, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for testQueryParameterCollectionFormat + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public okhttp3.Call testQueryParameterCollectionFormatCall(List pipe, List ioutil, List http, List url, List context, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake/test-query-parameters"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (pipe != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "pipe", pipe)); + } + + if (ioutil != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "ioutil", ioutil)); + } + + if (http != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("ssv", "http", http)); + } + + if (url != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "url", url)); + } + + if (context != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("multi", "context", context)); + } + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testQueryParameterCollectionFormatValidateBeforeCall(List pipe, List ioutil, List http, List url, List context, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'pipe' is set + if (pipe == null) { + throw new ApiException("Missing the required parameter 'pipe' when calling testQueryParameterCollectionFormat(Async)"); + } + + // verify the required parameter 'ioutil' is set + if (ioutil == null) { + throw new ApiException("Missing the required parameter 'ioutil' when calling testQueryParameterCollectionFormat(Async)"); + } + + // verify the required parameter 'http' is set + if (http == null) { + throw new ApiException("Missing the required parameter 'http' when calling testQueryParameterCollectionFormat(Async)"); + } + + // verify the required parameter 'url' is set + if (url == null) { + throw new ApiException("Missing the required parameter 'url' when calling testQueryParameterCollectionFormat(Async)"); + } + + // verify the required parameter 'context' is set + if (context == null) { + throw new ApiException("Missing the required parameter 'context' when calling testQueryParameterCollectionFormat(Async)"); + } + + + okhttp3.Call localVarCall = testQueryParameterCollectionFormatCall(pipe, ioutil, http, url, context, _callback); + return localVarCall; + + } + + /** + * + * To test the collection format in query parameters + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public void testQueryParameterCollectionFormat(List pipe, List ioutil, List http, List url, List context) throws ApiException { + testQueryParameterCollectionFormatWithHttpInfo(pipe, ioutil, http, url, context); + } + + /** + * + * To test the collection format in query parameters + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public ApiResponse testQueryParameterCollectionFormatWithHttpInfo(List pipe, List ioutil, List http, List url, List context) throws ApiException { + okhttp3.Call localVarCall = testQueryParameterCollectionFormatValidateBeforeCall(pipe, ioutil, http, url, context, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * (asynchronously) + * To test the collection format in query parameters + * @param pipe (required) + * @param ioutil (required) + * @param http (required) + * @param url (required) + * @param context (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 Success -
    + */ + public okhttp3.Call testQueryParameterCollectionFormatAsync(List pipe, List ioutil, List http, List url, List context, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testQueryParameterCollectionFormatValidateBeforeCall(pipe, ioutil, http, url, context, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java new file mode 100644 index 00000000000..f9449ed4420 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -0,0 +1,170 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; +import org.openapitools.client.ProgressRequestBody; +import org.openapitools.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import org.openapitools.client.model.Client; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeClassnameTags123Api { + private ApiClient localVarApiClient; + + public FakeClassnameTags123Api() { + this(Configuration.getDefaultApiClient()); + } + + public FakeClassnameTags123Api(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + /** + * Build call for testClassname + * @param client client model (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call testClassnameCall(Client client, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = client; + + // create path and map variables + String localVarPath = "/fake_classname_test"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "api_key_query" }; + return localVarApiClient.buildCall(localVarPath, "PATCH", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testClassnameValidateBeforeCall(Client client, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'client' is set + if (client == null) { + throw new ApiException("Missing the required parameter 'client' when calling testClassname(Async)"); + } + + + okhttp3.Call localVarCall = testClassnameCall(client, _callback); + return localVarCall; + + } + + /** + * To test class name in snake case + * To test class name in snake case + * @param client client model (required) + * @return Client + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public Client testClassname(Client client) throws ApiException { + ApiResponse localVarResp = testClassnameWithHttpInfo(client); + return localVarResp.getData(); + } + + /** + * To test class name in snake case + * To test class name in snake case + * @param client client model (required) + * @return ApiResponse<Client> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ApiResponse testClassnameWithHttpInfo(Client client) throws ApiException { + okhttp3.Call localVarCall = testClassnameValidateBeforeCall(client, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * To test class name in snake case (asynchronously) + * To test class name in snake case + * @param client client model (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call testClassnameAsync(Client client, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testClassnameValidateBeforeCall(client, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/PetApi.java new file mode 100644 index 00000000000..d88ee6f9c31 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/PetApi.java @@ -0,0 +1,1167 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; +import org.openapitools.client.ProgressRequestBody; +import org.openapitools.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class PetApi { + private ApiClient localVarApiClient; + + public PetApi() { + this(Configuration.getDefaultApiClient()); + } + + public PetApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + /** + * Build call for addPet + * @param pet Pet object that needs to be added to the store (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    405 Invalid input -
    + */ + public okhttp3.Call addPetCall(Pet pet, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = pet; + + // create path and map variables + String localVarPath = "/pet"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "http_signature_test", "petstore_auth" }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call addPetValidateBeforeCall(Pet pet, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'pet' is set + if (pet == null) { + throw new ApiException("Missing the required parameter 'pet' when calling addPet(Async)"); + } + + + okhttp3.Call localVarCall = addPetCall(pet, _callback); + return localVarCall; + + } + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    405 Invalid input -
    + */ + public void addPet(Pet pet) throws ApiException { + addPetWithHttpInfo(pet); + } + + /** + * Add a new pet to the store + * + * @param pet Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    405 Invalid input -
    + */ + public ApiResponse addPetWithHttpInfo(Pet pet) throws ApiException { + okhttp3.Call localVarCall = addPetValidateBeforeCall(pet, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Add a new pet to the store (asynchronously) + * + * @param pet Pet object that needs to be added to the store (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    405 Invalid input -
    + */ + public okhttp3.Call addPetAsync(Pet pet, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = addPetValidateBeforeCall(pet, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for deletePet + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    400 Invalid pet value -
    + */ + public okhttp3.Call deletePetCall(Long petId, String apiKey, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}" + .replaceAll("\\{" + "petId" + "\\}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (apiKey != null) { + localVarHeaderParams.put("api_key", localVarApiClient.parameterToString(apiKey)); + } + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call deletePetValidateBeforeCall(Long petId, String apiKey, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling deletePet(Async)"); + } + + + okhttp3.Call localVarCall = deletePetCall(petId, apiKey, _callback); + return localVarCall; + + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    400 Invalid pet value -
    + */ + public void deletePet(Long petId, String apiKey) throws ApiException { + deletePetWithHttpInfo(petId, apiKey); + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    400 Invalid pet value -
    + */ + public ApiResponse deletePetWithHttpInfo(Long petId, String apiKey) throws ApiException { + okhttp3.Call localVarCall = deletePetValidateBeforeCall(petId, apiKey, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Deletes a pet (asynchronously) + * + * @param petId Pet id to delete (required) + * @param apiKey (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    400 Invalid pet value -
    + */ + public okhttp3.Call deletePetAsync(Long petId, String apiKey, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = deletePetValidateBeforeCall(petId, apiKey, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for findPetsByStatus + * @param status Status values that need to be considered for filter (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid status value -
    + */ + public okhttp3.Call findPetsByStatusCall(List status, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/findByStatus"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (status != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "status", status)); + } + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "http_signature_test", "petstore_auth" }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call findPetsByStatusValidateBeforeCall(List status, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'status' is set + if (status == null) { + throw new ApiException("Missing the required parameter 'status' when calling findPetsByStatus(Async)"); + } + + + okhttp3.Call localVarCall = findPetsByStatusCall(status, _callback); + return localVarCall; + + } + + /** + * 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 List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid status value -
    + */ + public List findPetsByStatus(List status) throws ApiException { + ApiResponse> localVarResp = findPetsByStatusWithHttpInfo(status); + return localVarResp.getData(); + } + + /** + * 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 ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid status value -
    + */ + public ApiResponse> findPetsByStatusWithHttpInfo(List status) throws ApiException { + okhttp3.Call localVarCall = findPetsByStatusValidateBeforeCall(status, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Finds Pets by status (asynchronously) + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid status value -
    + */ + public okhttp3.Call findPetsByStatusAsync(List status, final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = findPetsByStatusValidateBeforeCall(status, _callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for findPetsByTags + * @param tags Tags to filter by (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid tag value -
    + * @deprecated + */ + @Deprecated + public okhttp3.Call findPetsByTagsCall(List tags, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/findByTags"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (tags != null) { + localVarCollectionQueryParams.addAll(localVarApiClient.parameterToPairs("csv", "tags", tags)); + } + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "http_signature_test", "petstore_auth" }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @Deprecated + @SuppressWarnings("rawtypes") + private okhttp3.Call findPetsByTagsValidateBeforeCall(List tags, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'tags' is set + if (tags == null) { + throw new ApiException("Missing the required parameter 'tags' when calling findPetsByTags(Async)"); + } + + + okhttp3.Call localVarCall = findPetsByTagsCall(tags, _callback); + return localVarCall; + + } + + /** + * 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 List<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid tag value -
    + * @deprecated + */ + @Deprecated + public List findPetsByTags(List tags) throws ApiException { + ApiResponse> localVarResp = findPetsByTagsWithHttpInfo(tags); + return localVarResp.getData(); + } + + /** + * 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 ApiResponse<List<Pet>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid tag value -
    + * @deprecated + */ + @Deprecated + public ApiResponse> findPetsByTagsWithHttpInfo(List tags) throws ApiException { + okhttp3.Call localVarCall = findPetsByTagsValidateBeforeCall(tags, null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Finds Pets by tags (asynchronously) + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid tag value -
    + * @deprecated + */ + @Deprecated + public okhttp3.Call findPetsByTagsAsync(List tags, final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = findPetsByTagsValidateBeforeCall(tags, _callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for getPetById + * @param petId ID of pet to return (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid ID supplied -
    404 Pet not found -
    + */ + public okhttp3.Call getPetByIdCall(Long petId, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}" + .replaceAll("\\{" + "petId" + "\\}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getPetByIdValidateBeforeCall(Long petId, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling getPetById(Async)"); + } + + + okhttp3.Call localVarCall = getPetByIdCall(petId, _callback); + return localVarCall; + + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid ID supplied -
    404 Pet not found -
    + */ + public Pet getPetById(Long petId) throws ApiException { + ApiResponse localVarResp = getPetByIdWithHttpInfo(petId); + return localVarResp.getData(); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return (required) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid ID supplied -
    404 Pet not found -
    + */ + public ApiResponse getPetByIdWithHttpInfo(Long petId) throws ApiException { + okhttp3.Call localVarCall = getPetByIdValidateBeforeCall(petId, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Find pet by ID (asynchronously) + * Returns a single pet + * @param petId ID of pet to return (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid ID supplied -
    404 Pet not found -
    + */ + public okhttp3.Call getPetByIdAsync(Long petId, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getPetByIdValidateBeforeCall(petId, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for updatePet + * @param pet Pet object that needs to be added to the store (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
    Status Code Description Response Headers
    400 Invalid ID supplied -
    404 Pet not found -
    405 Validation exception -
    + */ + public okhttp3.Call updatePetCall(Pet pet, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = pet; + + // create path and map variables + String localVarPath = "/pet"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json", "application/xml" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "http_signature_test", "petstore_auth" }; + return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call updatePetValidateBeforeCall(Pet pet, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'pet' is set + if (pet == null) { + throw new ApiException("Missing the required parameter 'pet' when calling updatePet(Async)"); + } + + + okhttp3.Call localVarCall = updatePetCall(pet, _callback); + return localVarCall; + + } + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
    Status Code Description Response Headers
    400 Invalid ID supplied -
    404 Pet not found -
    405 Validation exception -
    + */ + public void updatePet(Pet pet) throws ApiException { + updatePetWithHttpInfo(pet); + } + + /** + * Update an existing pet + * + * @param pet Pet object that needs to be added to the store (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
    Status Code Description Response Headers
    400 Invalid ID supplied -
    404 Pet not found -
    405 Validation exception -
    + */ + public ApiResponse updatePetWithHttpInfo(Pet pet) throws ApiException { + okhttp3.Call localVarCall = updatePetValidateBeforeCall(pet, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Update an existing pet (asynchronously) + * + * @param pet Pet object that needs to be added to the store (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
    Status Code Description Response Headers
    400 Invalid ID supplied -
    404 Pet not found -
    405 Validation exception -
    + */ + public okhttp3.Call updatePetAsync(Pet pet, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = updatePetValidateBeforeCall(pet, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for updatePetWithForm + * @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) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    405 Invalid input -
    + */ + public okhttp3.Call updatePetWithFormCall(Long petId, String name, String status, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}" + .replaceAll("\\{" + "petId" + "\\}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (name != null) { + localVarFormParams.put("name", name); + } + + if (status != null) { + localVarFormParams.put("status", status); + } + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call updatePetWithFormValidateBeforeCall(Long petId, String name, String status, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling updatePetWithForm(Async)"); + } + + + okhttp3.Call localVarCall = updatePetWithFormCall(petId, name, status, _callback); + return localVarCall; + + } + + /** + * 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) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    405 Invalid input -
    + */ + public void updatePetWithForm(Long petId, String name, String status) throws ApiException { + updatePetWithFormWithHttpInfo(petId, name, status); + } + + /** + * 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 ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    405 Invalid input -
    + */ + public ApiResponse updatePetWithFormWithHttpInfo(Long petId, String name, String status) throws ApiException { + okhttp3.Call localVarCall = updatePetWithFormValidateBeforeCall(petId, name, status, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Updates a pet in the store with form data (asynchronously) + * + * @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) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    405 Invalid input -
    + */ + public okhttp3.Call updatePetWithFormAsync(Long petId, String name, String status, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = updatePetWithFormValidateBeforeCall(petId, name, status, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for uploadFile + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call uploadFileCall(Long petId, String additionalMetadata, File file, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/pet/{petId}/uploadImage" + .replaceAll("\\{" + "petId" + "\\}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (additionalMetadata != null) { + localVarFormParams.put("additionalMetadata", additionalMetadata); + } + + if (file != null) { + localVarFormParams.put("file", file); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call uploadFileValidateBeforeCall(Long petId, String additionalMetadata, File file, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFile(Async)"); + } + + + okhttp3.Call localVarCall = uploadFileCall(petId, additionalMetadata, file, _callback); + return localVarCall; + + } + + /** + * 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 ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ModelApiResponse uploadFile(Long petId, String additionalMetadata, File file) throws ApiException { + ApiResponse localVarResp = uploadFileWithHttpInfo(petId, additionalMetadata, file); + return localVarResp.getData(); + } + + /** + * 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 ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ApiResponse uploadFileWithHttpInfo(Long petId, String additionalMetadata, File file) throws ApiException { + okhttp3.Call localVarCall = uploadFileValidateBeforeCall(petId, additionalMetadata, file, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * uploads an image (asynchronously) + * + * @param petId ID of pet to update (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call uploadFileAsync(Long petId, String additionalMetadata, File file, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = uploadFileValidateBeforeCall(petId, additionalMetadata, file, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for uploadFileWithRequiredFile + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call uploadFileWithRequiredFileCall(Long petId, File requiredFile, String additionalMetadata, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake/{petId}/uploadImageWithRequiredFile" + .replaceAll("\\{" + "petId" + "\\}", localVarApiClient.escapeString(petId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (additionalMetadata != null) { + localVarFormParams.put("additionalMetadata", additionalMetadata); + } + + if (requiredFile != null) { + localVarFormParams.put("requiredFile", requiredFile); + } + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "petstore_auth" }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call uploadFileWithRequiredFileValidateBeforeCall(Long petId, File requiredFile, String additionalMetadata, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'petId' is set + if (petId == null) { + throw new ApiException("Missing the required parameter 'petId' when calling uploadFileWithRequiredFile(Async)"); + } + + // verify the required parameter 'requiredFile' is set + if (requiredFile == null) { + throw new ApiException("Missing the required parameter 'requiredFile' when calling uploadFileWithRequiredFile(Async)"); + } + + + okhttp3.Call localVarCall = uploadFileWithRequiredFileCall(petId, requiredFile, additionalMetadata, _callback); + return localVarCall; + + } + + /** + * 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 ModelApiResponse + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ModelApiResponse uploadFileWithRequiredFile(Long petId, File requiredFile, String additionalMetadata) throws ApiException { + ApiResponse localVarResp = uploadFileWithRequiredFileWithHttpInfo(petId, requiredFile, additionalMetadata); + return localVarResp.getData(); + } + + /** + * 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 ApiResponse<ModelApiResponse> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ApiResponse uploadFileWithRequiredFileWithHttpInfo(Long petId, File requiredFile, String additionalMetadata) throws ApiException { + okhttp3.Call localVarCall = uploadFileWithRequiredFileValidateBeforeCall(petId, requiredFile, additionalMetadata, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * uploads an image (required) (asynchronously) + * + * @param petId ID of pet to update (required) + * @param requiredFile file to upload (required) + * @param additionalMetadata Additional data to pass to server (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call uploadFileWithRequiredFileAsync(Long petId, File requiredFile, String additionalMetadata, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = uploadFileWithRequiredFileValidateBeforeCall(petId, requiredFile, additionalMetadata, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/StoreApi.java new file mode 100644 index 00000000000..d9a068df9e9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/StoreApi.java @@ -0,0 +1,514 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; +import org.openapitools.client.ProgressRequestBody; +import org.openapitools.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import org.openapitools.client.model.Order; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class StoreApi { + private ApiClient localVarApiClient; + + public StoreApi() { + this(Configuration.getDefaultApiClient()); + } + + public StoreApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + /** + * Build call for deleteOrder + * @param orderId ID of the order that needs to be deleted (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid ID supplied -
    404 Order not found -
    + */ + public okhttp3.Call deleteOrderCall(String orderId, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/order/{order_id}" + .replaceAll("\\{" + "order_id" + "\\}", localVarApiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call deleteOrderValidateBeforeCall(String orderId, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling deleteOrder(Async)"); + } + + + okhttp3.Call localVarCall = deleteOrderCall(orderId, _callback); + return localVarCall; + + } + + /** + * 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) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid ID supplied -
    404 Order not found -
    + */ + public void deleteOrder(String orderId) throws ApiException { + deleteOrderWithHttpInfo(orderId); + } + + /** + * 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 ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid ID supplied -
    404 Order not found -
    + */ + public ApiResponse deleteOrderWithHttpInfo(String orderId) throws ApiException { + okhttp3.Call localVarCall = deleteOrderValidateBeforeCall(orderId, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Delete purchase order by ID (asynchronously) + * 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) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid ID supplied -
    404 Order not found -
    + */ + public okhttp3.Call deleteOrderAsync(String orderId, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = deleteOrderValidateBeforeCall(orderId, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for getInventory + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call getInventoryCall(final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/inventory"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "api_key" }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getInventoryValidateBeforeCall(final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = getInventoryCall(_callback); + return localVarCall; + + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return Map<String, Integer> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public Map getInventory() throws ApiException { + ApiResponse> localVarResp = getInventoryWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse<Map<String, Integer>> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public ApiResponse> getInventoryWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = getInventoryValidateBeforeCall(null); + Type localVarReturnType = new TypeToken>(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Returns pet inventories by status (asynchronously) + * Returns a map of status codes to quantities + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    200 successful operation -
    + */ + public okhttp3.Call getInventoryAsync(final ApiCallback> _callback) throws ApiException { + + okhttp3.Call localVarCall = getInventoryValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken>(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for getOrderById + * @param orderId ID of pet that needs to be fetched (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid ID supplied -
    404 Order not found -
    + */ + public okhttp3.Call getOrderByIdCall(Long orderId, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/store/order/{order_id}" + .replaceAll("\\{" + "order_id" + "\\}", localVarApiClient.escapeString(orderId.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getOrderByIdValidateBeforeCall(Long orderId, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'orderId' is set + if (orderId == null) { + throw new ApiException("Missing the required parameter 'orderId' when calling getOrderById(Async)"); + } + + + okhttp3.Call localVarCall = getOrderByIdCall(orderId, _callback); + return localVarCall; + + } + + /** + * 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 Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid ID supplied -
    404 Order not found -
    + */ + public Order getOrderById(Long orderId) throws ApiException { + ApiResponse localVarResp = getOrderByIdWithHttpInfo(orderId); + return localVarResp.getData(); + } + + /** + * 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 ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid ID supplied -
    404 Order not found -
    + */ + public ApiResponse getOrderByIdWithHttpInfo(Long orderId) throws ApiException { + okhttp3.Call localVarCall = getOrderByIdValidateBeforeCall(orderId, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Find purchase order by ID (asynchronously) + * 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) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid ID supplied -
    404 Order not found -
    + */ + public okhttp3.Call getOrderByIdAsync(Long orderId, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getOrderByIdValidateBeforeCall(orderId, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for placeOrder + * @param order order placed for purchasing the pet (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid Order -
    + */ + public okhttp3.Call placeOrderCall(Order order, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = order; + + // create path and map variables + String localVarPath = "/store/order"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call placeOrderValidateBeforeCall(Order order, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'order' is set + if (order == null) { + throw new ApiException("Missing the required parameter 'order' when calling placeOrder(Async)"); + } + + + okhttp3.Call localVarCall = placeOrderCall(order, _callback); + return localVarCall; + + } + + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet (required) + * @return Order + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid Order -
    + */ + public Order placeOrder(Order order) throws ApiException { + ApiResponse localVarResp = placeOrderWithHttpInfo(order); + return localVarResp.getData(); + } + + /** + * Place an order for a pet + * + * @param order order placed for purchasing the pet (required) + * @return ApiResponse<Order> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid Order -
    + */ + public ApiResponse placeOrderWithHttpInfo(Order order) throws ApiException { + okhttp3.Call localVarCall = placeOrderValidateBeforeCall(order, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Place an order for a pet (asynchronously) + * + * @param order order placed for purchasing the pet (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid Order -
    + */ + public okhttp3.Call placeOrderAsync(Order order, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = placeOrderValidateBeforeCall(order, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/UserApi.java new file mode 100644 index 00000000000..0f4f2d294a4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/api/UserApi.java @@ -0,0 +1,977 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; +import org.openapitools.client.ProgressRequestBody; +import org.openapitools.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import org.openapitools.client.model.User; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class UserApi { + private ApiClient localVarApiClient; + + public UserApi() { + this(Configuration.getDefaultApiClient()); + } + + public UserApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + /** + * Build call for createUser + * @param user Created user object (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public okhttp3.Call createUserCall(User user, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = user; + + // create path and map variables + String localVarPath = "/user"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call createUserValidateBeforeCall(User user, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling createUser(Async)"); + } + + + okhttp3.Call localVarCall = createUserCall(user, _callback); + return localVarCall; + + } + + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public void createUser(User user) throws ApiException { + createUserWithHttpInfo(user); + } + + /** + * Create user + * This can only be done by the logged in user. + * @param user Created user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public ApiResponse createUserWithHttpInfo(User user) throws ApiException { + okhttp3.Call localVarCall = createUserValidateBeforeCall(user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Create user (asynchronously) + * This can only be done by the logged in user. + * @param user Created user object (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public okhttp3.Call createUserAsync(User user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = createUserValidateBeforeCall(user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for createUsersWithArrayInput + * @param user List of user object (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public okhttp3.Call createUsersWithArrayInputCall(List user, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = user; + + // create path and map variables + String localVarPath = "/user/createWithArray"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call createUsersWithArrayInputValidateBeforeCall(List user, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling createUsersWithArrayInput(Async)"); + } + + + okhttp3.Call localVarCall = createUsersWithArrayInputCall(user, _callback); + return localVarCall; + + } + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public void createUsersWithArrayInput(List user) throws ApiException { + createUsersWithArrayInputWithHttpInfo(user); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public ApiResponse createUsersWithArrayInputWithHttpInfo(List user) throws ApiException { + okhttp3.Call localVarCall = createUsersWithArrayInputValidateBeforeCall(user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param user List of user object (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public okhttp3.Call createUsersWithArrayInputAsync(List user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = createUsersWithArrayInputValidateBeforeCall(user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for createUsersWithListInput + * @param user List of user object (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public okhttp3.Call createUsersWithListInputCall(List user, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = user; + + // create path and map variables + String localVarPath = "/user/createWithList"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call createUsersWithListInputValidateBeforeCall(List user, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling createUsersWithListInput(Async)"); + } + + + okhttp3.Call localVarCall = createUsersWithListInputCall(user, _callback); + return localVarCall; + + } + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public void createUsersWithListInput(List user) throws ApiException { + createUsersWithListInputWithHttpInfo(user); + } + + /** + * Creates list of users with given input array + * + * @param user List of user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public ApiResponse createUsersWithListInputWithHttpInfo(List user) throws ApiException { + okhttp3.Call localVarCall = createUsersWithListInputValidateBeforeCall(user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Creates list of users with given input array (asynchronously) + * + * @param user List of user object (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public okhttp3.Call createUsersWithListInputAsync(List user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = createUsersWithListInputValidateBeforeCall(user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for deleteUser + * @param username The name that needs to be deleted (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid username supplied -
    404 User not found -
    + */ + public okhttp3.Call deleteUserCall(String username, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/{username}" + .replaceAll("\\{" + "username" + "\\}", localVarApiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call deleteUserValidateBeforeCall(String username, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling deleteUser(Async)"); + } + + + okhttp3.Call localVarCall = deleteUserCall(username, _callback); + return localVarCall; + + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid username supplied -
    404 User not found -
    + */ + public void deleteUser(String username) throws ApiException { + deleteUserWithHttpInfo(username); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid username supplied -
    404 User not found -
    + */ + public ApiResponse deleteUserWithHttpInfo(String username) throws ApiException { + okhttp3.Call localVarCall = deleteUserValidateBeforeCall(username, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Delete user (asynchronously) + * This can only be done by the logged in user. + * @param username The name that needs to be deleted (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid username supplied -
    404 User not found -
    + */ + public okhttp3.Call deleteUserAsync(String username, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = deleteUserValidateBeforeCall(username, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for getUserByName + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid username supplied -
    404 User not found -
    + */ + public okhttp3.Call getUserByNameCall(String username, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/{username}" + .replaceAll("\\{" + "username" + "\\}", localVarApiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call getUserByNameValidateBeforeCall(String username, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling getUserByName(Async)"); + } + + + okhttp3.Call localVarCall = getUserByNameCall(username, _callback); + return localVarCall; + + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return User + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid username supplied -
    404 User not found -
    + */ + public User getUserByName(String username) throws ApiException { + ApiResponse localVarResp = getUserByNameWithHttpInfo(username); + return localVarResp.getData(); + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return ApiResponse<User> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid username supplied -
    404 User not found -
    + */ + public ApiResponse getUserByNameWithHttpInfo(String username) throws ApiException { + okhttp3.Call localVarCall = getUserByNameValidateBeforeCall(username, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Get user by user name (asynchronously) + * + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + + +
    Status Code Description Response Headers
    200 successful operation -
    400 Invalid username supplied -
    404 User not found -
    + */ + public okhttp3.Call getUserByNameAsync(String username, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = getUserByNameValidateBeforeCall(username, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for loginUser + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation * X-Rate-Limit - calls per hour allowed by the user
    * X-Expires-After - date in UTC when token expires
    400 Invalid username/password supplied -
    + */ + public okhttp3.Call loginUserCall(String username, String password, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/login"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (username != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("username", username)); + } + + if (password != null) { + localVarQueryParams.addAll(localVarApiClient.parameterToPair("password", password)); + } + + final String[] localVarAccepts = { + "application/xml", "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call loginUserValidateBeforeCall(String username, String password, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling loginUser(Async)"); + } + + // verify the required parameter 'password' is set + if (password == null) { + throw new ApiException("Missing the required parameter 'password' when calling loginUser(Async)"); + } + + + okhttp3.Call localVarCall = loginUserCall(username, password, _callback); + return localVarCall; + + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation * X-Rate-Limit - calls per hour allowed by the user
    * X-Expires-After - date in UTC when token expires
    400 Invalid username/password supplied -
    + */ + public String loginUser(String username, String password) throws ApiException { + ApiResponse localVarResp = loginUserWithHttpInfo(username, password); + return localVarResp.getData(); + } + + /** + * Logs user into the system + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation * X-Rate-Limit - calls per hour allowed by the user
    * X-Expires-After - date in UTC when token expires
    400 Invalid username/password supplied -
    + */ + public ApiResponse loginUserWithHttpInfo(String username, String password) throws ApiException { + okhttp3.Call localVarCall = loginUserValidateBeforeCall(username, password, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Logs user into the system (asynchronously) + * + * @param username The user name for login (required) + * @param password The password for login in clear text (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    200 successful operation * X-Rate-Limit - calls per hour allowed by the user
    * X-Expires-After - date in UTC when token expires
    400 Invalid username/password supplied -
    + */ + public okhttp3.Call loginUserAsync(String username, String password, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = loginUserValidateBeforeCall(username, password, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for logoutUser + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public okhttp3.Call logoutUserCall(final ApiCallback _callback) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/user/logout"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call logoutUserValidateBeforeCall(final ApiCallback _callback) throws ApiException { + + + okhttp3.Call localVarCall = logoutUserCall(_callback); + return localVarCall; + + } + + /** + * Logs out current logged in user session + * + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public void logoutUser() throws ApiException { + logoutUserWithHttpInfo(); + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public ApiResponse logoutUserWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = logoutUserValidateBeforeCall(null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Logs out current logged in user session (asynchronously) + * + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
    Status Code Description Response Headers
    0 successful operation -
    + */ + public okhttp3.Call logoutUserAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = logoutUserValidateBeforeCall(_callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } + /** + * Build call for updateUser + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid user supplied -
    404 User not found -
    + */ + public okhttp3.Call updateUserCall(String username, User user, final ApiCallback _callback) throws ApiException { + Object localVarPostBody = user; + + // create path and map variables + String localVarPath = "/user/{username}" + .replaceAll("\\{" + "username" + "\\}", localVarApiClient.escapeString(username.toString())); + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarHeaderParams != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call updateUserValidateBeforeCall(String username, User user, final ApiCallback _callback) throws ApiException { + + // verify the required parameter 'username' is set + if (username == null) { + throw new ApiException("Missing the required parameter 'username' when calling updateUser(Async)"); + } + + // verify the required parameter 'user' is set + if (user == null) { + throw new ApiException("Missing the required parameter 'user' when calling updateUser(Async)"); + } + + + okhttp3.Call localVarCall = updateUserCall(username, user, _callback); + return localVarCall; + + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid user supplied -
    404 User not found -
    + */ + public void updateUser(String username, User user) throws ApiException { + updateUserWithHttpInfo(username, user); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid user supplied -
    404 User not found -
    + */ + public ApiResponse updateUserWithHttpInfo(String username, User user) throws ApiException { + okhttp3.Call localVarCall = updateUserValidateBeforeCall(username, user, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * Updated user (asynchronously) + * This can only be done by the logged in user. + * @param username name that need to be deleted (required) + * @param user Updated user object (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + + +
    Status Code Description Response Headers
    400 Invalid user supplied -
    404 User not found -
    + */ + public okhttp3.Call updateUserAsync(String username, User user, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = updateUserValidateBeforeCall(username, user, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 00000000000..35aa7184d26 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,80 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +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/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 00000000000..c59d11e0ce9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,36 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.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 + * @param payload HTTP request body + * @param method HTTP method + * @param uri URI + * @throws ApiException if failed to update the parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 00000000000..b4641c4217c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,57 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import okhttp3.Credentials; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +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; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java new file mode 100644 index 00000000000..460ad224963 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -0,0 +1,63 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +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/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuth.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuth.java new file mode 100644 index 00000000000..08a855ec5f9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuth.java @@ -0,0 +1,42 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.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 OAuth implements Authentication { + private String accessToken; + + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + if (accessToken != null) { + headerParams.put("Authorization", "Bearer " + accessToken); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuthFlow.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuthFlow.java new file mode 100644 index 00000000000..ac3ecef0020 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuthFlow.java @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public enum OAuthFlow { + accessCode, //called authorizationCode in OpenAPI 3.0 + implicit, + password, + application //called clientCredentials in OpenAPI 3.0 +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuthOkHttpClient.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuthOkHttpClient.java new file mode 100644 index 00000000000..1c8ac2dc0cc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/OAuthOkHttpClient.java @@ -0,0 +1,68 @@ +package org.openapitools.client.auth; + +import okhttp3.OkHttpClient; +import okhttp3.MediaType; +import okhttp3.Request; +import okhttp3.RequestBody; +import okhttp3.Response; + +import org.apache.oltu.oauth2.client.HttpClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthClientResponse; +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; + +import java.io.IOException; +import java.util.Map; +import java.util.Map.Entry; + +public class OAuthOkHttpClient implements HttpClient { + private OkHttpClient client; + + public OAuthOkHttpClient() { + this.client = new OkHttpClient(); + } + + public OAuthOkHttpClient(OkHttpClient client) { + this.client = client; + } + + @Override + public T execute(OAuthClientRequest request, Map headers, + String requestMethod, Class responseClass) + throws OAuthSystemException, OAuthProblemException { + + MediaType mediaType = MediaType.parse("application/json"); + Request.Builder requestBuilder = new Request.Builder().url(request.getLocationUri()); + + if(headers != null) { + for (Entry entry : headers.entrySet()) { + if (entry.getKey().equalsIgnoreCase("Content-Type")) { + mediaType = MediaType.parse(entry.getValue()); + } else { + requestBuilder.addHeader(entry.getKey(), entry.getValue()); + } + } + } + + RequestBody body = request.getBody() != null ? RequestBody.create(request.getBody(), mediaType) : null; + requestBuilder.method(requestMethod, body); + + try { + Response response = client.newCall(requestBuilder.build()).execute(); + return OAuthClientResponseFactory.createCustomResponse( + response.body().string(), + response.body().contentType().toString(), + response.code(), + responseClass); + } catch (IOException e) { + throw new OAuthSystemException(e); + } + } + + @Override + public void shutdown() { + // Nothing to do here + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/RetryingOAuth.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/RetryingOAuth.java new file mode 100644 index 00000000000..911df8d3a37 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/auth/RetryingOAuth.java @@ -0,0 +1,182 @@ +package org.openapitools.client.auth; + +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +import okhttp3.Interceptor; +import okhttp3.OkHttpClient; +import okhttp3.Request; +import okhttp3.Response; + +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.apache.oltu.oauth2.common.message.types.GrantType; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.net.URI; +import java.util.Map; +import java.util.List; + +public class RetryingOAuth extends OAuth implements Interceptor { + private OAuthClient oAuthClient; + + private TokenRequestBuilder tokenRequestBuilder; + + public RetryingOAuth(OkHttpClient client, TokenRequestBuilder tokenRequestBuilder) { + this.oAuthClient = new OAuthClient(new OAuthOkHttpClient(client)); + this.tokenRequestBuilder = tokenRequestBuilder; + } + + public RetryingOAuth(TokenRequestBuilder tokenRequestBuilder) { + this(new OkHttpClient(), tokenRequestBuilder); + } + + /** + @param tokenUrl The token URL to be used for this OAuth2 flow. + Applicable to the following OAuth2 flows: "password", "clientCredentials" and "authorizationCode". + The value must be an absolute URL. + @param clientId The OAuth2 client ID for the "clientCredentials" flow. + @param clientSecret The OAuth2 client secret for the "clientCredentials" flow. + */ + public RetryingOAuth( + String tokenUrl, + String clientId, + OAuthFlow flow, + String clientSecret, + Map parameters + ) { + this(OAuthClientRequest.tokenLocation(tokenUrl) + .setClientId(clientId) + .setClientSecret(clientSecret)); + setFlow(flow); + if (parameters != null) { + for (String paramName : parameters.keySet()) { + tokenRequestBuilder.setParameter(paramName, parameters.get(paramName)); + } + } + } + + public void setFlow(OAuthFlow flow) { + switch(flow) { + case accessCode: + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE); + break; + case implicit: + tokenRequestBuilder.setGrantType(GrantType.IMPLICIT); + break; + case password: + tokenRequestBuilder.setGrantType(GrantType.PASSWORD); + break; + case application: + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS); + break; + default: + break; + } + } + + @Override + public Response intercept(Chain chain) throws IOException { + return retryingIntercept(chain, true); + } + + private Response retryingIntercept(Chain chain, boolean updateTokenAndRetryOnAuthorizationFailure) throws IOException { + Request request = chain.request(); + + // If the request already has an authorization (e.g. Basic auth), proceed with the request as is + if (request.header("Authorization") != null) { + return chain.proceed(request); + } + + // Get the token if it has not yet been acquired + if (getAccessToken() == null) { + updateAccessToken(null); + } + + OAuthClientRequest oAuthRequest; + if (getAccessToken() != null) { + // Build the request + Request.Builder requestBuilder = request.newBuilder(); + + String requestAccessToken = getAccessToken(); + try { + oAuthRequest = + new OAuthBearerClientRequest(request.url().toString()). + setAccessToken(requestAccessToken). + buildHeaderMessage(); + } catch (OAuthSystemException e) { + throw new IOException(e); + } + + Map headers = oAuthRequest.getHeaders(); + for (String headerName : headers.keySet()) { + requestBuilder.addHeader(headerName, headers.get(headerName)); + } + requestBuilder.url(oAuthRequest.getLocationUri()); + + // Execute the request + Response response = chain.proceed(requestBuilder.build()); + + // 401/403 response codes most likely indicate an expired access token, unless it happens two times in a row + if ( + response != null && + ( response.code() == HttpURLConnection.HTTP_UNAUTHORIZED || + response.code() == HttpURLConnection.HTTP_FORBIDDEN ) && + updateTokenAndRetryOnAuthorizationFailure + ) { + try { + if (updateAccessToken(requestAccessToken)) { + response.body().close(); + return retryingIntercept(chain, false); + } + } catch (Exception e) { + response.body().close(); + throw e; + } + } + return response; + } + else { + return chain.proceed(chain.request()); + } + } + + /* + * Returns true if the access token has been updated + */ + public synchronized boolean updateAccessToken(String requestAccessToken) throws IOException { + if (getAccessToken() == null || getAccessToken().equals(requestAccessToken)) { + try { + OAuthJSONAccessTokenResponse accessTokenResponse = + oAuthClient.accessToken(tokenRequestBuilder.buildBodyMessage()); + if (accessTokenResponse != null && accessTokenResponse.getAccessToken() != null) { + setAccessToken(accessTokenResponse.getAccessToken()); + } + } catch (OAuthSystemException | OAuthProblemException e) { + throw new IOException(e); + } + } + return getAccessToken() == null || !getAccessToken().equals(requestAccessToken); + } + + public TokenRequestBuilder getTokenRequestBuilder() { + return tokenRequestBuilder; + } + + public void setTokenRequestBuilder(TokenRequestBuilder tokenRequestBuilder) { + this.tokenRequestBuilder = tokenRequestBuilder; + } + + // Applying authorization to parameters is performed in the retryingIntercept method + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + // No implementation necessary + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java new file mode 100644 index 00000000000..ddda27d5fed --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -0,0 +1,149 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.openapitools.client.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 nullable + * + * @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/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java new file mode 100644 index 00000000000..5c1d5c3fd66 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -0,0 +1,419 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * AdditionalPropertiesClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AdditionalPropertiesClass { + public static final String SERIALIZED_NAME_MAP_PROPERTY = "map_property"; + @SerializedName(SERIALIZED_NAME_MAP_PROPERTY) + private Map mapProperty = null; + + public static final String SERIALIZED_NAME_MAP_OF_MAP_PROPERTY = "map_of_map_property"; + @SerializedName(SERIALIZED_NAME_MAP_OF_MAP_PROPERTY) + private Map> mapOfMapProperty = null; + + public static final String SERIALIZED_NAME_ANYTYPE1 = "anytype_1"; + @SerializedName(SERIALIZED_NAME_ANYTYPE1) + private Object anytype1 = null; + + public static final String SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE1 = "map_with_undeclared_properties_anytype_1"; + @SerializedName(SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE1) + private Object mapWithUndeclaredPropertiesAnytype1; + + public static final String SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE2 = "map_with_undeclared_properties_anytype_2"; + @SerializedName(SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE2) + private Object mapWithUndeclaredPropertiesAnytype2; + + public static final String SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE3 = "map_with_undeclared_properties_anytype_3"; + @SerializedName(SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_ANYTYPE3) + private Map mapWithUndeclaredPropertiesAnytype3 = null; + + public static final String SERIALIZED_NAME_EMPTY_MAP = "empty_map"; + @SerializedName(SERIALIZED_NAME_EMPTY_MAP) + private Object emptyMap; + + public static final String SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_STRING = "map_with_undeclared_properties_string"; + @SerializedName(SERIALIZED_NAME_MAP_WITH_UNDECLARED_PROPERTIES_STRING) + private Map mapWithUndeclaredPropertiesString = null; + + public AdditionalPropertiesClass() { + } + + public AdditionalPropertiesClass mapProperty(Map mapProperty) { + + this.mapProperty = mapProperty; + return this; + } + + public AdditionalPropertiesClass putMapPropertyItem(String key, String mapPropertyItem) { + if (this.mapProperty == null) { + this.mapProperty = new HashMap(); + } + this.mapProperty.put(key, mapPropertyItem); + return this; + } + + /** + * Get mapProperty + * @return mapProperty + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getMapProperty() { + return mapProperty; + } + + + public void setMapProperty(Map mapProperty) { + this.mapProperty = mapProperty; + } + + + public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { + + this.mapOfMapProperty = mapOfMapProperty; + return this; + } + + public AdditionalPropertiesClass putMapOfMapPropertyItem(String key, Map mapOfMapPropertyItem) { + if (this.mapOfMapProperty == null) { + this.mapOfMapProperty = new HashMap>(); + } + this.mapOfMapProperty.put(key, mapOfMapPropertyItem); + return this; + } + + /** + * Get mapOfMapProperty + * @return mapOfMapProperty + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map> getMapOfMapProperty() { + return mapOfMapProperty; + } + + + public void setMapOfMapProperty(Map> mapOfMapProperty) { + this.mapOfMapProperty = mapOfMapProperty; + } + + + public AdditionalPropertiesClass anytype1(Object anytype1) { + + this.anytype1 = anytype1; + return this; + } + + /** + * Get anytype1 + * @return anytype1 + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Object getAnytype1() { + return anytype1; + } + + + public void setAnytype1(Object anytype1) { + this.anytype1 = anytype1; + } + + + public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype1(Object mapWithUndeclaredPropertiesAnytype1) { + + this.mapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; + return this; + } + + /** + * Get mapWithUndeclaredPropertiesAnytype1 + * @return mapWithUndeclaredPropertiesAnytype1 + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Object getMapWithUndeclaredPropertiesAnytype1() { + return mapWithUndeclaredPropertiesAnytype1; + } + + + public void setMapWithUndeclaredPropertiesAnytype1(Object mapWithUndeclaredPropertiesAnytype1) { + this.mapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; + } + + + public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype2(Object mapWithUndeclaredPropertiesAnytype2) { + + this.mapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; + return this; + } + + /** + * Get mapWithUndeclaredPropertiesAnytype2 + * @return mapWithUndeclaredPropertiesAnytype2 + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Object getMapWithUndeclaredPropertiesAnytype2() { + return mapWithUndeclaredPropertiesAnytype2; + } + + + public void setMapWithUndeclaredPropertiesAnytype2(Object mapWithUndeclaredPropertiesAnytype2) { + this.mapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; + } + + + public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype3(Map mapWithUndeclaredPropertiesAnytype3) { + + this.mapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; + return this; + } + + public AdditionalPropertiesClass putMapWithUndeclaredPropertiesAnytype3Item(String key, Object mapWithUndeclaredPropertiesAnytype3Item) { + if (this.mapWithUndeclaredPropertiesAnytype3 == null) { + this.mapWithUndeclaredPropertiesAnytype3 = new HashMap(); + } + this.mapWithUndeclaredPropertiesAnytype3.put(key, mapWithUndeclaredPropertiesAnytype3Item); + return this; + } + + /** + * Get mapWithUndeclaredPropertiesAnytype3 + * @return mapWithUndeclaredPropertiesAnytype3 + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getMapWithUndeclaredPropertiesAnytype3() { + return mapWithUndeclaredPropertiesAnytype3; + } + + + public void setMapWithUndeclaredPropertiesAnytype3(Map mapWithUndeclaredPropertiesAnytype3) { + this.mapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; + } + + + public AdditionalPropertiesClass emptyMap(Object emptyMap) { + + this.emptyMap = emptyMap; + return this; + } + + /** + * an object with no declared properties and no undeclared properties, hence it's an empty map. + * @return emptyMap + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "an object with no declared properties and no undeclared properties, hence it's an empty map.") + + public Object getEmptyMap() { + return emptyMap; + } + + + public void setEmptyMap(Object emptyMap) { + this.emptyMap = emptyMap; + } + + + public AdditionalPropertiesClass mapWithUndeclaredPropertiesString(Map mapWithUndeclaredPropertiesString) { + + this.mapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + return this; + } + + public AdditionalPropertiesClass putMapWithUndeclaredPropertiesStringItem(String key, String mapWithUndeclaredPropertiesStringItem) { + if (this.mapWithUndeclaredPropertiesString == null) { + this.mapWithUndeclaredPropertiesString = new HashMap(); + } + this.mapWithUndeclaredPropertiesString.put(key, mapWithUndeclaredPropertiesStringItem); + return this; + } + + /** + * Get mapWithUndeclaredPropertiesString + * @return mapWithUndeclaredPropertiesString + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getMapWithUndeclaredPropertiesString() { + return mapWithUndeclaredPropertiesString; + } + + + public void setMapWithUndeclaredPropertiesString(Map mapWithUndeclaredPropertiesString) { + this.mapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty) && + Objects.equals(this.anytype1, additionalPropertiesClass.anytype1) && + Objects.equals(this.mapWithUndeclaredPropertiesAnytype1, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype1) && + Objects.equals(this.mapWithUndeclaredPropertiesAnytype2, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype2) && + Objects.equals(this.mapWithUndeclaredPropertiesAnytype3, additionalPropertiesClass.mapWithUndeclaredPropertiesAnytype3) && + Objects.equals(this.emptyMap, additionalPropertiesClass.emptyMap) && + Objects.equals(this.mapWithUndeclaredPropertiesString, additionalPropertiesClass.mapWithUndeclaredPropertiesString); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(mapProperty, mapOfMapProperty, anytype1, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, emptyMap, mapWithUndeclaredPropertiesString); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AdditionalPropertiesClass {\n"); + sb.append(" mapProperty: ").append(toIndentedString(mapProperty)).append("\n"); + sb.append(" mapOfMapProperty: ").append(toIndentedString(mapOfMapProperty)).append("\n"); + sb.append(" anytype1: ").append(toIndentedString(anytype1)).append("\n"); + sb.append(" mapWithUndeclaredPropertiesAnytype1: ").append(toIndentedString(mapWithUndeclaredPropertiesAnytype1)).append("\n"); + sb.append(" mapWithUndeclaredPropertiesAnytype2: ").append(toIndentedString(mapWithUndeclaredPropertiesAnytype2)).append("\n"); + sb.append(" mapWithUndeclaredPropertiesAnytype3: ").append(toIndentedString(mapWithUndeclaredPropertiesAnytype3)).append("\n"); + sb.append(" emptyMap: ").append(toIndentedString(emptyMap)).append("\n"); + sb.append(" mapWithUndeclaredPropertiesString: ").append(toIndentedString(mapWithUndeclaredPropertiesString)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("map_property"); + openapiFields.add("map_of_map_property"); + openapiFields.add("anytype_1"); + openapiFields.add("map_with_undeclared_properties_anytype_1"); + openapiFields.add("map_with_undeclared_properties_anytype_2"); + openapiFields.add("map_with_undeclared_properties_anytype_3"); + openapiFields.add("empty_map"); + openapiFields.add("map_with_undeclared_properties_string"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AdditionalPropertiesClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AdditionalPropertiesClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AdditionalPropertiesClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AdditionalPropertiesClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AdditionalPropertiesClass read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!AdditionalPropertiesClass.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `AdditionalPropertiesClass` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java new file mode 100644 index 00000000000..cf1f00de64f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java @@ -0,0 +1,203 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Cat; +import org.openapitools.client.model.Dog; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Animal + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Animal { + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + protected String className; + + public static final String SERIALIZED_NAME_COLOR = "color"; + @SerializedName(SERIALIZED_NAME_COLOR) + private String color = "red"; + + public Animal() { + this.className = this.getClass().getSimpleName(); + } + + public Animal className(String className) { + + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getClassName() { + return className; + } + + + public void setClassName(String className) { + this.className = className; + } + + + public Animal color(String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getColor() { + return color; + } + + + public void setColor(String color) { + this.color = color; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Animal {\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("className"); + openapiFields.add("color"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("className"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Animal.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Animal' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Animal.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Animal value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Animal read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Animal.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Animal` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Animal.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Apple.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Apple.java new file mode 100644 index 00000000000..03e3cc0f9c8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Apple.java @@ -0,0 +1,192 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Apple + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Apple { + public static final String SERIALIZED_NAME_CULTIVAR = "cultivar"; + @SerializedName(SERIALIZED_NAME_CULTIVAR) + private String cultivar; + + public static final String SERIALIZED_NAME_ORIGIN = "origin"; + @SerializedName(SERIALIZED_NAME_ORIGIN) + private String origin; + + public Apple() { + } + + public Apple cultivar(String cultivar) { + + this.cultivar = cultivar; + return this; + } + + /** + * Get cultivar + * @return cultivar + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getCultivar() { + return cultivar; + } + + + public void setCultivar(String cultivar) { + this.cultivar = cultivar; + } + + + public Apple origin(String origin) { + + this.origin = origin; + return this; + } + + /** + * Get origin + * @return origin + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getOrigin() { + return origin; + } + + + public void setOrigin(String origin) { + this.origin = origin; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Apple apple = (Apple) o; + return Objects.equals(this.cultivar, apple.cultivar) && + Objects.equals(this.origin, apple.origin); + } + + @Override + public int hashCode() { + return Objects.hash(cultivar, origin); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Apple {\n"); + sb.append(" cultivar: ").append(toIndentedString(cultivar)).append("\n"); + sb.append(" origin: ").append(toIndentedString(origin)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("cultivar"); + openapiFields.add("origin"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Apple.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Apple' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Apple.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Apple value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Apple read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Apple.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Apple` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AppleReq.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AppleReq.java new file mode 100644 index 00000000000..dbf82279534 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/AppleReq.java @@ -0,0 +1,200 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * AppleReq + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AppleReq { + public static final String SERIALIZED_NAME_CULTIVAR = "cultivar"; + @SerializedName(SERIALIZED_NAME_CULTIVAR) + private String cultivar; + + public static final String SERIALIZED_NAME_MEALY = "mealy"; + @SerializedName(SERIALIZED_NAME_MEALY) + private Boolean mealy; + + public AppleReq() { + } + + public AppleReq cultivar(String cultivar) { + + this.cultivar = cultivar; + return this; + } + + /** + * Get cultivar + * @return cultivar + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getCultivar() { + return cultivar; + } + + + public void setCultivar(String cultivar) { + this.cultivar = cultivar; + } + + + public AppleReq mealy(Boolean mealy) { + + this.mealy = mealy; + return this; + } + + /** + * Get mealy + * @return mealy + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Boolean getMealy() { + return mealy; + } + + + public void setMealy(Boolean mealy) { + this.mealy = mealy; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AppleReq appleReq = (AppleReq) o; + return Objects.equals(this.cultivar, appleReq.cultivar) && + Objects.equals(this.mealy, appleReq.mealy); + } + + @Override + public int hashCode() { + return Objects.hash(cultivar, mealy); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AppleReq {\n"); + sb.append(" cultivar: ").append(toIndentedString(cultivar)).append("\n"); + sb.append(" mealy: ").append(toIndentedString(mealy)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("cultivar"); + openapiFields.add("mealy"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("cultivar"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AppleReq.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AppleReq' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AppleReq.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AppleReq value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public AppleReq read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!AppleReq.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `AppleReq` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : AppleReq.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java new file mode 100644 index 00000000000..2dc3a695404 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -0,0 +1,173 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ArrayOfArrayOfNumberOnly + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ArrayOfArrayOfNumberOnly { + public static final String SERIALIZED_NAME_ARRAY_ARRAY_NUMBER = "ArrayArrayNumber"; + @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_NUMBER) + private List> arrayArrayNumber = null; + + public ArrayOfArrayOfNumberOnly() { + } + + public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { + + this.arrayArrayNumber = arrayArrayNumber; + return this; + } + + public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayArrayNumberItem) { + if (this.arrayArrayNumber == null) { + this.arrayArrayNumber = new ArrayList>(); + } + this.arrayArrayNumber.add(arrayArrayNumberItem); + return this; + } + + /** + * Get arrayArrayNumber + * @return arrayArrayNumber + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List> getArrayArrayNumber() { + return arrayArrayNumber; + } + + + public void setArrayArrayNumber(List> arrayArrayNumber) { + this.arrayArrayNumber = arrayArrayNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfArrayOfNumberOnly {\n"); + sb.append(" arrayArrayNumber: ").append(toIndentedString(arrayArrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("ArrayArrayNumber"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfArrayOfNumberOnly.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfArrayOfNumberOnly' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfArrayOfNumberOnly.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfArrayOfNumberOnly value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfArrayOfNumberOnly read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ArrayOfArrayOfNumberOnly.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ArrayOfArrayOfNumberOnly` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java new file mode 100644 index 00000000000..384759be851 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -0,0 +1,173 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ArrayOfNumberOnly + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ArrayOfNumberOnly { + public static final String SERIALIZED_NAME_ARRAY_NUMBER = "ArrayNumber"; + @SerializedName(SERIALIZED_NAME_ARRAY_NUMBER) + private List arrayNumber = null; + + public ArrayOfNumberOnly() { + } + + public ArrayOfNumberOnly arrayNumber(List arrayNumber) { + + this.arrayNumber = arrayNumber; + return this; + } + + public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { + if (this.arrayNumber == null) { + this.arrayNumber = new ArrayList(); + } + this.arrayNumber.add(arrayNumberItem); + return this; + } + + /** + * Get arrayNumber + * @return arrayNumber + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getArrayNumber() { + return arrayNumber; + } + + + public void setArrayNumber(List arrayNumber) { + this.arrayNumber = arrayNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayOfNumberOnly {\n"); + sb.append(" arrayNumber: ").append(toIndentedString(arrayNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("ArrayNumber"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayOfNumberOnly.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayOfNumberOnly' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayOfNumberOnly.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayOfNumberOnly value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ArrayOfNumberOnly read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ArrayOfNumberOnly.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ArrayOfNumberOnly` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayTest.java new file mode 100644 index 00000000000..23c8d4fbd1b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -0,0 +1,249 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ReadOnlyFirst; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ArrayTest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ArrayTest { + public static final String SERIALIZED_NAME_ARRAY_OF_STRING = "array_of_string"; + @SerializedName(SERIALIZED_NAME_ARRAY_OF_STRING) + private List arrayOfString = null; + + public static final String SERIALIZED_NAME_ARRAY_ARRAY_OF_INTEGER = "array_array_of_integer"; + @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_INTEGER) + private List> arrayArrayOfInteger = null; + + public static final String SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; + @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) + private List> arrayArrayOfModel = null; + + public ArrayTest() { + } + + public ArrayTest arrayOfString(List arrayOfString) { + + this.arrayOfString = arrayOfString; + return this; + } + + public ArrayTest addArrayOfStringItem(String arrayOfStringItem) { + if (this.arrayOfString == null) { + this.arrayOfString = new ArrayList(); + } + this.arrayOfString.add(arrayOfStringItem); + return this; + } + + /** + * Get arrayOfString + * @return arrayOfString + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getArrayOfString() { + return arrayOfString; + } + + + public void setArrayOfString(List arrayOfString) { + this.arrayOfString = arrayOfString; + } + + + public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { + + this.arrayArrayOfInteger = arrayArrayOfInteger; + return this; + } + + public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) { + if (this.arrayArrayOfInteger == null) { + this.arrayArrayOfInteger = new ArrayList>(); + } + this.arrayArrayOfInteger.add(arrayArrayOfIntegerItem); + return this; + } + + /** + * Get arrayArrayOfInteger + * @return arrayArrayOfInteger + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List> getArrayArrayOfInteger() { + return arrayArrayOfInteger; + } + + + public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { + this.arrayArrayOfInteger = arrayArrayOfInteger; + } + + + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + + this.arrayArrayOfModel = arrayArrayOfModel; + return this; + } + + public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + if (this.arrayArrayOfModel == null) { + this.arrayArrayOfModel = new ArrayList>(); + } + this.arrayArrayOfModel.add(arrayArrayOfModelItem); + return this; + } + + /** + * Get arrayArrayOfModel + * @return arrayArrayOfModel + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List> getArrayArrayOfModel() { + return arrayArrayOfModel; + } + + + public void setArrayArrayOfModel(List> arrayArrayOfModel) { + this.arrayArrayOfModel = arrayArrayOfModel; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ArrayTest {\n"); + sb.append(" arrayOfString: ").append(toIndentedString(arrayOfString)).append("\n"); + sb.append(" arrayArrayOfInteger: ").append(toIndentedString(arrayArrayOfInteger)).append("\n"); + sb.append(" arrayArrayOfModel: ").append(toIndentedString(arrayArrayOfModel)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("array_of_string"); + openapiFields.add("array_array_of_integer"); + openapiFields.add("array_array_of_model"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ArrayTest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ArrayTest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ArrayTest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ArrayTest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ArrayTest read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ArrayTest.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ArrayTest` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Banana.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Banana.java new file mode 100644 index 00000000000..e409ac6907a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Banana.java @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Banana + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Banana { + public static final String SERIALIZED_NAME_LENGTH_CM = "lengthCm"; + @SerializedName(SERIALIZED_NAME_LENGTH_CM) + private BigDecimal lengthCm; + + public Banana() { + } + + public Banana lengthCm(BigDecimal lengthCm) { + + this.lengthCm = lengthCm; + return this; + } + + /** + * Get lengthCm + * @return lengthCm + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public BigDecimal getLengthCm() { + return lengthCm; + } + + + public void setLengthCm(BigDecimal lengthCm) { + this.lengthCm = lengthCm; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Banana banana = (Banana) o; + return Objects.equals(this.lengthCm, banana.lengthCm); + } + + @Override + public int hashCode() { + return Objects.hash(lengthCm); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Banana {\n"); + sb.append(" lengthCm: ").append(toIndentedString(lengthCm)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("lengthCm"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Banana.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Banana' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Banana.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Banana value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Banana read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Banana.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Banana` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/BananaReq.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/BananaReq.java new file mode 100644 index 00000000000..7955096b5d3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/BananaReq.java @@ -0,0 +1,201 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * BananaReq + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class BananaReq { + public static final String SERIALIZED_NAME_LENGTH_CM = "lengthCm"; + @SerializedName(SERIALIZED_NAME_LENGTH_CM) + private BigDecimal lengthCm; + + public static final String SERIALIZED_NAME_SWEET = "sweet"; + @SerializedName(SERIALIZED_NAME_SWEET) + private Boolean sweet; + + public BananaReq() { + } + + public BananaReq lengthCm(BigDecimal lengthCm) { + + this.lengthCm = lengthCm; + return this; + } + + /** + * Get lengthCm + * @return lengthCm + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public BigDecimal getLengthCm() { + return lengthCm; + } + + + public void setLengthCm(BigDecimal lengthCm) { + this.lengthCm = lengthCm; + } + + + public BananaReq sweet(Boolean sweet) { + + this.sweet = sweet; + return this; + } + + /** + * Get sweet + * @return sweet + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Boolean getSweet() { + return sweet; + } + + + public void setSweet(Boolean sweet) { + this.sweet = sweet; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BananaReq bananaReq = (BananaReq) o; + return Objects.equals(this.lengthCm, bananaReq.lengthCm) && + Objects.equals(this.sweet, bananaReq.sweet); + } + + @Override + public int hashCode() { + return Objects.hash(lengthCm, sweet); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BananaReq {\n"); + sb.append(" lengthCm: ").append(toIndentedString(lengthCm)).append("\n"); + sb.append(" sweet: ").append(toIndentedString(sweet)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("lengthCm"); + openapiFields.add("sweet"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("lengthCm"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!BananaReq.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'BananaReq' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(BananaReq.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, BananaReq value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public BananaReq read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!BananaReq.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `BananaReq` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : BananaReq.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/BasquePig.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/BasquePig.java new file mode 100644 index 00000000000..93fc4cad0b9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/BasquePig.java @@ -0,0 +1,170 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * BasquePig + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class BasquePig { + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + private String className; + + public BasquePig() { + } + + public BasquePig className(String className) { + + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getClassName() { + return className; + } + + + public void setClassName(String className) { + this.className = className; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BasquePig basquePig = (BasquePig) o; + return Objects.equals(this.className, basquePig.className); + } + + @Override + public int hashCode() { + return Objects.hash(className); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class BasquePig {\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("className"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("className"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!BasquePig.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'BasquePig' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(BasquePig.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, BasquePig value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public BasquePig read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!BasquePig.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `BasquePig` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : BasquePig.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Capitalization.java new file mode 100644 index 00000000000..eceb83bbfeb --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Capitalization.java @@ -0,0 +1,312 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Capitalization + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Capitalization { + public static final String SERIALIZED_NAME_SMALL_CAMEL = "smallCamel"; + @SerializedName(SERIALIZED_NAME_SMALL_CAMEL) + private String smallCamel; + + public static final String SERIALIZED_NAME_CAPITAL_CAMEL = "CapitalCamel"; + @SerializedName(SERIALIZED_NAME_CAPITAL_CAMEL) + private String capitalCamel; + + public static final String SERIALIZED_NAME_SMALL_SNAKE = "small_Snake"; + @SerializedName(SERIALIZED_NAME_SMALL_SNAKE) + private String smallSnake; + + public static final String SERIALIZED_NAME_CAPITAL_SNAKE = "Capital_Snake"; + @SerializedName(SERIALIZED_NAME_CAPITAL_SNAKE) + private String capitalSnake; + + public static final String SERIALIZED_NAME_SC_A_E_T_H_FLOW_POINTS = "SCA_ETH_Flow_Points"; + @SerializedName(SERIALIZED_NAME_SC_A_E_T_H_FLOW_POINTS) + private String scAETHFlowPoints; + + public static final String SERIALIZED_NAME_A_T_T_N_A_M_E = "ATT_NAME"; + @SerializedName(SERIALIZED_NAME_A_T_T_N_A_M_E) + private String ATT_NAME; + + public Capitalization() { + } + + public Capitalization smallCamel(String smallCamel) { + + this.smallCamel = smallCamel; + return this; + } + + /** + * Get smallCamel + * @return smallCamel + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getSmallCamel() { + return smallCamel; + } + + + public void setSmallCamel(String smallCamel) { + this.smallCamel = smallCamel; + } + + + public Capitalization capitalCamel(String capitalCamel) { + + this.capitalCamel = capitalCamel; + return this; + } + + /** + * Get capitalCamel + * @return capitalCamel + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getCapitalCamel() { + return capitalCamel; + } + + + public void setCapitalCamel(String capitalCamel) { + this.capitalCamel = capitalCamel; + } + + + public Capitalization smallSnake(String smallSnake) { + + this.smallSnake = smallSnake; + return this; + } + + /** + * Get smallSnake + * @return smallSnake + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getSmallSnake() { + return smallSnake; + } + + + public void setSmallSnake(String smallSnake) { + this.smallSnake = smallSnake; + } + + + public Capitalization capitalSnake(String capitalSnake) { + + this.capitalSnake = capitalSnake; + return this; + } + + /** + * Get capitalSnake + * @return capitalSnake + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getCapitalSnake() { + return capitalSnake; + } + + + public void setCapitalSnake(String capitalSnake) { + this.capitalSnake = capitalSnake; + } + + + public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { + + this.scAETHFlowPoints = scAETHFlowPoints; + return this; + } + + /** + * Get scAETHFlowPoints + * @return scAETHFlowPoints + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getScAETHFlowPoints() { + return scAETHFlowPoints; + } + + + public void setScAETHFlowPoints(String scAETHFlowPoints) { + this.scAETHFlowPoints = scAETHFlowPoints; + } + + + public Capitalization ATT_NAME(String ATT_NAME) { + + this.ATT_NAME = ATT_NAME; + return this; + } + + /** + * Name of the pet + * @return ATT_NAME + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "Name of the pet ") + + public String getATTNAME() { + return ATT_NAME; + } + + + public void setATTNAME(String ATT_NAME) { + this.ATT_NAME = ATT_NAME; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Capitalization {\n"); + sb.append(" smallCamel: ").append(toIndentedString(smallCamel)).append("\n"); + sb.append(" capitalCamel: ").append(toIndentedString(capitalCamel)).append("\n"); + sb.append(" smallSnake: ").append(toIndentedString(smallSnake)).append("\n"); + sb.append(" capitalSnake: ").append(toIndentedString(capitalSnake)).append("\n"); + sb.append(" scAETHFlowPoints: ").append(toIndentedString(scAETHFlowPoints)).append("\n"); + sb.append(" ATT_NAME: ").append(toIndentedString(ATT_NAME)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("smallCamel"); + openapiFields.add("CapitalCamel"); + openapiFields.add("small_Snake"); + openapiFields.add("Capital_Snake"); + openapiFields.add("SCA_ETH_Flow_Points"); + openapiFields.add("ATT_NAME"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Capitalization.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Capitalization' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Capitalization.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Capitalization value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Capitalization read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Capitalization.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Capitalization` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Cat.java new file mode 100644 index 00000000000..426511dc3c0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Cat.java @@ -0,0 +1,177 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Animal; +import org.openapitools.client.model.CatAllOf; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Cat + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Cat extends Animal { + public static final String SERIALIZED_NAME_DECLAWED = "declawed"; + @SerializedName(SERIALIZED_NAME_DECLAWED) + private Boolean declawed; + + public Cat() { + this.className = this.getClass().getSimpleName(); + } + + public Cat declawed(Boolean declawed) { + + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Boolean getDeclawed() { + return declawed; + } + + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return Objects.equals(this.declawed, cat.declawed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(declawed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Cat {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("className"); + openapiFields.add("color"); + openapiFields.add("declawed"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("className"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Cat.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Cat' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Cat.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Cat value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Cat read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Cat.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Cat` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Cat.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/CatAllOf.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/CatAllOf.java new file mode 100644 index 00000000000..8d9affba3dc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/CatAllOf.java @@ -0,0 +1,162 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * CatAllOf + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class CatAllOf { + public static final String SERIALIZED_NAME_DECLAWED = "declawed"; + @SerializedName(SERIALIZED_NAME_DECLAWED) + private Boolean declawed; + + public CatAllOf() { + } + + public CatAllOf declawed(Boolean declawed) { + + this.declawed = declawed; + return this; + } + + /** + * Get declawed + * @return declawed + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Boolean getDeclawed() { + return declawed; + } + + + public void setDeclawed(Boolean declawed) { + this.declawed = declawed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + CatAllOf catAllOf = (CatAllOf) o; + return Objects.equals(this.declawed, catAllOf.declawed); + } + + @Override + public int hashCode() { + return Objects.hash(declawed); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class CatAllOf {\n"); + sb.append(" declawed: ").append(toIndentedString(declawed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("declawed"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!CatAllOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'CatAllOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(CatAllOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, CatAllOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public CatAllOf read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!CatAllOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `CatAllOf` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Category.java new file mode 100644 index 00000000000..85eb92c71b2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Category.java @@ -0,0 +1,200 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Category + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Category { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + private String name = "default-name"; + + public Category() { + } + + public Category id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Category name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("id"); + openapiFields.add("name"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("name"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Category.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Category' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Category.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Category value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Category read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Category.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Category` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Category.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ChildCatAllOf.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ChildCatAllOf.java new file mode 100644 index 00000000000..6932fbcef5a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ChildCatAllOf.java @@ -0,0 +1,216 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ChildCatAllOf + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ChildCatAllOf { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + private String name; + + /** + * Gets or Sets petType + */ + @JsonAdapter(PetTypeEnum.Adapter.class) + public enum PetTypeEnum { + CHILDCAT("ChildCat"); + + private String value; + + PetTypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static PetTypeEnum fromValue(String value) { + for (PetTypeEnum b : PetTypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final PetTypeEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public PetTypeEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return PetTypeEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_PET_TYPE = "pet_type"; + @SerializedName(SERIALIZED_NAME_PET_TYPE) + private PetTypeEnum petType = PetTypeEnum.CHILDCAT; + + public ChildCatAllOf() { + } + + public ChildCatAllOf name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + public ChildCatAllOf petType(PetTypeEnum petType) { + + this.petType = petType; + return this; + } + + /** + * Get petType + * @return petType + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public PetTypeEnum getPetType() { + return petType; + } + + + public void setPetType(PetTypeEnum petType) { + this.petType = petType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ChildCatAllOf childCatAllOf = (ChildCatAllOf) o; + return Objects.equals(this.name, childCatAllOf.name) && + Objects.equals(this.petType, childCatAllOf.petType); + } + + @Override + public int hashCode() { + return Objects.hash(name, petType); + } + + @Override + 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(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("name"); + openapiFields.add("pet_type"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomDeserializer implements JsonDeserializer { + @Override + public ChildCatAllOf deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { + JsonObject obj = json.getAsJsonObject(); //since you know it's a JsonObject + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ChildCatAllOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ChildCatAllOf` properties"); + } + } + + // all checks passed, return using the original implementation of deserialize + return new Gson().fromJson(json, ChildCatAllOf.class); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ClassModel.java new file mode 100644 index 00000000000..da8517ec7b9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ClassModel.java @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Model for testing model with \"_class\" property + */ +@ApiModel(description = "Model for testing model with \"_class\" property") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ClassModel { + public static final String SERIALIZED_NAME_PROPERTY_CLASS = "_class"; + @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) + private String propertyClass; + + public ClassModel() { + } + + public ClassModel propertyClass(String propertyClass) { + + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getPropertyClass() { + return propertyClass; + } + + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(this.propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ClassModel {\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("_class"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ClassModel.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ClassModel' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ClassModel.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ClassModel value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ClassModel read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ClassModel.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ClassModel` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Client.java new file mode 100644 index 00000000000..2a7cf96170c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Client.java @@ -0,0 +1,162 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Client + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Client { + public static final String SERIALIZED_NAME_CLIENT = "client"; + @SerializedName(SERIALIZED_NAME_CLIENT) + private String client; + + public Client() { + } + + public Client client(String client) { + + this.client = client; + return this; + } + + /** + * Get client + * @return client + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getClient() { + return client; + } + + + public void setClient(String client) { + this.client = client; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(this.client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Client {\n"); + sb.append(" client: ").append(toIndentedString(client)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("client"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Client.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Client' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Client.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Client value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Client read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Client.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Client` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java new file mode 100644 index 00000000000..197a8ca0a22 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java @@ -0,0 +1,203 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.QuadrilateralInterface; +import org.openapitools.client.model.ShapeInterface; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ComplexQuadrilateral + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ComplexQuadrilateral { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + private String shapeType; + + public static final String SERIALIZED_NAME_QUADRILATERAL_TYPE = "quadrilateralType"; + @SerializedName(SERIALIZED_NAME_QUADRILATERAL_TYPE) + private String quadrilateralType; + + public ComplexQuadrilateral() { + } + + public ComplexQuadrilateral shapeType(String shapeType) { + + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getShapeType() { + return shapeType; + } + + + public void setShapeType(String shapeType) { + this.shapeType = shapeType; + } + + + public ComplexQuadrilateral quadrilateralType(String quadrilateralType) { + + this.quadrilateralType = quadrilateralType; + return this; + } + + /** + * Get quadrilateralType + * @return quadrilateralType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getQuadrilateralType() { + return quadrilateralType; + } + + + public void setQuadrilateralType(String quadrilateralType) { + this.quadrilateralType = quadrilateralType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ComplexQuadrilateral complexQuadrilateral = (ComplexQuadrilateral) o; + return Objects.equals(this.shapeType, complexQuadrilateral.shapeType) && + Objects.equals(this.quadrilateralType, complexQuadrilateral.quadrilateralType); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, quadrilateralType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ComplexQuadrilateral {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" quadrilateralType: ").append(toIndentedString(quadrilateralType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("shapeType"); + openapiFields.add("quadrilateralType"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("shapeType"); + openapiRequiredFields.add("quadrilateralType"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ComplexQuadrilateral.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ComplexQuadrilateral' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ComplexQuadrilateral.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ComplexQuadrilateral value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ComplexQuadrilateral read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ComplexQuadrilateral.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ComplexQuadrilateral` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : ComplexQuadrilateral.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DanishPig.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DanishPig.java new file mode 100644 index 00000000000..c9bdd6fb478 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DanishPig.java @@ -0,0 +1,170 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * DanishPig + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DanishPig { + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + private String className; + + public DanishPig() { + } + + public DanishPig className(String className) { + + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getClassName() { + return className; + } + + + public void setClassName(String className) { + this.className = className; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DanishPig danishPig = (DanishPig) o; + return Objects.equals(this.className, danishPig.className); + } + + @Override + public int hashCode() { + return Objects.hash(className); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DanishPig {\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("className"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("className"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DanishPig.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DanishPig' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DanishPig.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DanishPig value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public DanishPig read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!DanishPig.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `DanishPig` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : DanishPig.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DeprecatedObject.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DeprecatedObject.java new file mode 100644 index 00000000000..1ebdc75845b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DeprecatedObject.java @@ -0,0 +1,164 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * DeprecatedObject + * @deprecated + */ +@Deprecated +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DeprecatedObject { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + private String name; + + public DeprecatedObject() { + } + + public DeprecatedObject name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DeprecatedObject deprecatedObject = (DeprecatedObject) o; + return Objects.equals(this.name, deprecatedObject.name); + } + + @Override + public int hashCode() { + return Objects.hash(name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DeprecatedObject {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("name"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DeprecatedObject.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DeprecatedObject' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DeprecatedObject.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DeprecatedObject value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public DeprecatedObject read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!DeprecatedObject.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `DeprecatedObject` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Dog.java new file mode 100644 index 00000000000..407d20c326a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Dog.java @@ -0,0 +1,177 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Animal; +import org.openapitools.client.model.DogAllOf; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Dog + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Dog extends Animal { + public static final String SERIALIZED_NAME_BREED = "breed"; + @SerializedName(SERIALIZED_NAME_BREED) + private String breed; + + public Dog() { + this.className = this.getClass().getSimpleName(); + } + + public Dog breed(String breed) { + + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getBreed() { + return breed; + } + + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return Objects.equals(this.breed, dog.breed) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(breed, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Dog {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("className"); + openapiFields.add("color"); + openapiFields.add("breed"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("className"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Dog.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Dog' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Dog.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Dog value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Dog read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Dog.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Dog` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Dog.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DogAllOf.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DogAllOf.java new file mode 100644 index 00000000000..4305b501e06 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/DogAllOf.java @@ -0,0 +1,162 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * DogAllOf + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DogAllOf { + public static final String SERIALIZED_NAME_BREED = "breed"; + @SerializedName(SERIALIZED_NAME_BREED) + private String breed; + + public DogAllOf() { + } + + public DogAllOf breed(String breed) { + + this.breed = breed; + return this; + } + + /** + * Get breed + * @return breed + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getBreed() { + return breed; + } + + + public void setBreed(String breed) { + this.breed = breed; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DogAllOf dogAllOf = (DogAllOf) o; + return Objects.equals(this.breed, dogAllOf.breed); + } + + @Override + public int hashCode() { + return Objects.hash(breed); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DogAllOf {\n"); + sb.append(" breed: ").append(toIndentedString(breed)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("breed"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!DogAllOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'DogAllOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(DogAllOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, DogAllOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public DogAllOf read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!DogAllOf.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `DogAllOf` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Drawing.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Drawing.java new file mode 100644 index 00000000000..b880f4c49dd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Drawing.java @@ -0,0 +1,282 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.client.model.Fruit; +import org.openapitools.client.model.NullableShape; +import org.openapitools.client.model.Shape; +import org.openapitools.client.model.ShapeOrNull; +import org.openapitools.jackson.nullable.JsonNullable; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Drawing + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Drawing extends HashMap { + public static final String SERIALIZED_NAME_MAIN_SHAPE = "mainShape"; + @SerializedName(SERIALIZED_NAME_MAIN_SHAPE) + private Shape mainShape; + + public static final String SERIALIZED_NAME_SHAPE_OR_NULL = "shapeOrNull"; + @SerializedName(SERIALIZED_NAME_SHAPE_OR_NULL) + private ShapeOrNull shapeOrNull; + + public static final String SERIALIZED_NAME_NULLABLE_SHAPE = "nullableShape"; + @SerializedName(SERIALIZED_NAME_NULLABLE_SHAPE) + private NullableShape nullableShape; + + public static final String SERIALIZED_NAME_SHAPES = "shapes"; + @SerializedName(SERIALIZED_NAME_SHAPES) + private List shapes = null; + + public Drawing() { + } + + public Drawing mainShape(Shape mainShape) { + + this.mainShape = mainShape; + return this; + } + + /** + * Get mainShape + * @return mainShape + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Shape getMainShape() { + return mainShape; + } + + + public void setMainShape(Shape mainShape) { + this.mainShape = mainShape; + } + + + public Drawing shapeOrNull(ShapeOrNull shapeOrNull) { + + this.shapeOrNull = shapeOrNull; + return this; + } + + /** + * Get shapeOrNull + * @return shapeOrNull + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public ShapeOrNull getShapeOrNull() { + return shapeOrNull; + } + + + public void setShapeOrNull(ShapeOrNull shapeOrNull) { + this.shapeOrNull = shapeOrNull; + } + + + public Drawing nullableShape(NullableShape nullableShape) { + + this.nullableShape = nullableShape; + return this; + } + + /** + * Get nullableShape + * @return nullableShape + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public NullableShape getNullableShape() { + return nullableShape; + } + + + public void setNullableShape(NullableShape nullableShape) { + this.nullableShape = nullableShape; + } + + + public Drawing shapes(List shapes) { + + this.shapes = shapes; + return this; + } + + public Drawing addShapesItem(Shape shapesItem) { + if (this.shapes == null) { + this.shapes = new ArrayList(); + } + this.shapes.add(shapesItem); + return this; + } + + /** + * Get shapes + * @return shapes + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getShapes() { + return shapes; + } + + + public void setShapes(List shapes) { + this.shapes = shapes; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Drawing drawing = (Drawing) o; + return Objects.equals(this.mainShape, drawing.mainShape) && + Objects.equals(this.shapeOrNull, drawing.shapeOrNull) && + Objects.equals(this.nullableShape, drawing.nullableShape) && + Objects.equals(this.shapes, drawing.shapes) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(mainShape, shapeOrNull, nullableShape, shapes, super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Drawing {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" mainShape: ").append(toIndentedString(mainShape)).append("\n"); + sb.append(" shapeOrNull: ").append(toIndentedString(shapeOrNull)).append("\n"); + sb.append(" nullableShape: ").append(toIndentedString(nullableShape)).append("\n"); + sb.append(" shapes: ").append(toIndentedString(shapes)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("mainShape"); + openapiFields.add("shapeOrNull"); + openapiFields.add("nullableShape"); + openapiFields.add("shapes"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Drawing.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Drawing' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Drawing.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Drawing value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Drawing read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Drawing.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Drawing` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumArrays.java new file mode 100644 index 00000000000..87675e4eef7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -0,0 +1,296 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * EnumArrays + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class EnumArrays { + /** + * Gets or Sets justSymbol + */ + @JsonAdapter(JustSymbolEnum.Adapter.class) + public enum JustSymbolEnum { + GREATER_THAN_OR_EQUAL_TO(">="), + + DOLLAR("$"); + + private String value; + + JustSymbolEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static JustSymbolEnum fromValue(String value) { + for (JustSymbolEnum b : JustSymbolEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final JustSymbolEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public JustSymbolEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return JustSymbolEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_JUST_SYMBOL = "just_symbol"; + @SerializedName(SERIALIZED_NAME_JUST_SYMBOL) + private JustSymbolEnum justSymbol; + + /** + * Gets or Sets arrayEnum + */ + @JsonAdapter(ArrayEnumEnum.Adapter.class) + public enum ArrayEnumEnum { + FISH("fish"), + + CRAB("crab"); + + private String value; + + ArrayEnumEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static ArrayEnumEnum fromValue(String value) { + for (ArrayEnumEnum b : ArrayEnumEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final ArrayEnumEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public ArrayEnumEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return ArrayEnumEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_ARRAY_ENUM = "array_enum"; + @SerializedName(SERIALIZED_NAME_ARRAY_ENUM) + private List arrayEnum = null; + + public EnumArrays() { + } + + public EnumArrays justSymbol(JustSymbolEnum justSymbol) { + + this.justSymbol = justSymbol; + return this; + } + + /** + * Get justSymbol + * @return justSymbol + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public JustSymbolEnum getJustSymbol() { + return justSymbol; + } + + + public void setJustSymbol(JustSymbolEnum justSymbol) { + this.justSymbol = justSymbol; + } + + + public EnumArrays arrayEnum(List arrayEnum) { + + this.arrayEnum = arrayEnum; + return this; + } + + public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { + if (this.arrayEnum == null) { + this.arrayEnum = new ArrayList(); + } + this.arrayEnum.add(arrayEnumItem); + return this; + } + + /** + * Get arrayEnum + * @return arrayEnum + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getArrayEnum() { + return arrayEnum; + } + + + public void setArrayEnum(List arrayEnum) { + this.arrayEnum = arrayEnum; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumArrays {\n"); + sb.append(" justSymbol: ").append(toIndentedString(justSymbol)).append("\n"); + sb.append(" arrayEnum: ").append(toIndentedString(arrayEnum)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("just_symbol"); + openapiFields.add("array_enum"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!EnumArrays.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'EnumArrays' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(EnumArrays.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, EnumArrays value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public EnumArrays read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!EnumArrays.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `EnumArrays` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumClass.java new file mode 100644 index 00000000000..b9a78241a5a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumClass.java @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Gets or Sets EnumClass + */ +@JsonAdapter(EnumClass.Adapter.class) +public enum EnumClass { + + _ABC("_abc"), + + _EFG("-efg"), + + _XYZ_("(xyz)"); + + private String value; + + EnumClass(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumClass fromValue(String value) { + for (EnumClass b : EnumClass.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumClass enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumClass read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return EnumClass.fromValue(value); + } + } +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumTest.java new file mode 100644 index 00000000000..8bb57d811f0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EnumTest.java @@ -0,0 +1,665 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.OuterEnumDefaultValue; +import org.openapitools.client.model.OuterEnumInteger; +import org.openapitools.client.model.OuterEnumIntegerDefaultValue; +import org.openapitools.jackson.nullable.JsonNullable; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * EnumTest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class EnumTest { + /** + * Gets or Sets enumString + */ + @JsonAdapter(EnumStringEnum.Adapter.class) + public enum EnumStringEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringEnum fromValue(String value) { + for (EnumStringEnum b : EnumStringEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumStringEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumStringEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return EnumStringEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_ENUM_STRING = "enum_string"; + @SerializedName(SERIALIZED_NAME_ENUM_STRING) + private EnumStringEnum enumString; + + /** + * Gets or Sets enumStringRequired + */ + @JsonAdapter(EnumStringRequiredEnum.Adapter.class) + public enum EnumStringRequiredEnum { + UPPER("UPPER"), + + LOWER("lower"), + + EMPTY(""); + + private String value; + + EnumStringRequiredEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumStringRequiredEnum fromValue(String value) { + for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumStringRequiredEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumStringRequiredEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return EnumStringRequiredEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_ENUM_STRING_REQUIRED = "enum_string_required"; + @SerializedName(SERIALIZED_NAME_ENUM_STRING_REQUIRED) + private EnumStringRequiredEnum enumStringRequired; + + /** + * Gets or Sets enumInteger + */ + @JsonAdapter(EnumIntegerEnum.Adapter.class) + public enum EnumIntegerEnum { + NUMBER_1(1), + + NUMBER_MINUS_1(-1); + + private Integer value; + + EnumIntegerEnum(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumIntegerEnum fromValue(Integer value) { + for (EnumIntegerEnum b : EnumIntegerEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumIntegerEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumIntegerEnum read(final JsonReader jsonReader) throws IOException { + Integer value = jsonReader.nextInt(); + return EnumIntegerEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_ENUM_INTEGER = "enum_integer"; + @SerializedName(SERIALIZED_NAME_ENUM_INTEGER) + private EnumIntegerEnum enumInteger; + + /** + * Gets or Sets enumIntegerOnly + */ + @JsonAdapter(EnumIntegerOnlyEnum.Adapter.class) + public enum EnumIntegerOnlyEnum { + NUMBER_2(2), + + NUMBER_MINUS_2(-2); + + private Integer value; + + EnumIntegerOnlyEnum(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumIntegerOnlyEnum fromValue(Integer value) { + for (EnumIntegerOnlyEnum b : EnumIntegerOnlyEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumIntegerOnlyEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumIntegerOnlyEnum read(final JsonReader jsonReader) throws IOException { + Integer value = jsonReader.nextInt(); + return EnumIntegerOnlyEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_ENUM_INTEGER_ONLY = "enum_integer_only"; + @SerializedName(SERIALIZED_NAME_ENUM_INTEGER_ONLY) + private EnumIntegerOnlyEnum enumIntegerOnly; + + /** + * Gets or Sets enumNumber + */ + @JsonAdapter(EnumNumberEnum.Adapter.class) + public enum EnumNumberEnum { + NUMBER_1_DOT_1(1.1), + + NUMBER_MINUS_1_DOT_2(-1.2); + + private Double value; + + EnumNumberEnum(Double value) { + this.value = value; + } + + public Double getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static EnumNumberEnum fromValue(Double value) { + for (EnumNumberEnum b : EnumNumberEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final EnumNumberEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public EnumNumberEnum read(final JsonReader jsonReader) throws IOException { + Double value = jsonReader.nextDouble(); + return EnumNumberEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_ENUM_NUMBER = "enum_number"; + @SerializedName(SERIALIZED_NAME_ENUM_NUMBER) + private EnumNumberEnum enumNumber; + + public static final String SERIALIZED_NAME_OUTER_ENUM = "outerEnum"; + @SerializedName(SERIALIZED_NAME_OUTER_ENUM) + private OuterEnum outerEnum; + + public static final String SERIALIZED_NAME_OUTER_ENUM_INTEGER = "outerEnumInteger"; + @SerializedName(SERIALIZED_NAME_OUTER_ENUM_INTEGER) + private OuterEnumInteger outerEnumInteger; + + public static final String SERIALIZED_NAME_OUTER_ENUM_DEFAULT_VALUE = "outerEnumDefaultValue"; + @SerializedName(SERIALIZED_NAME_OUTER_ENUM_DEFAULT_VALUE) + private OuterEnumDefaultValue outerEnumDefaultValue = OuterEnumDefaultValue.PLACED; + + public static final String SERIALIZED_NAME_OUTER_ENUM_INTEGER_DEFAULT_VALUE = "outerEnumIntegerDefaultValue"; + @SerializedName(SERIALIZED_NAME_OUTER_ENUM_INTEGER_DEFAULT_VALUE) + private OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue = OuterEnumIntegerDefaultValue.NUMBER_0; + + public EnumTest() { + } + + public EnumTest enumString(EnumStringEnum enumString) { + + this.enumString = enumString; + return this; + } + + /** + * Get enumString + * @return enumString + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public EnumStringEnum getEnumString() { + return enumString; + } + + + public void setEnumString(EnumStringEnum enumString) { + this.enumString = enumString; + } + + + public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { + + this.enumStringRequired = enumStringRequired; + return this; + } + + /** + * Get enumStringRequired + * @return enumStringRequired + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public EnumStringRequiredEnum getEnumStringRequired() { + return enumStringRequired; + } + + + public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { + this.enumStringRequired = enumStringRequired; + } + + + public EnumTest enumInteger(EnumIntegerEnum enumInteger) { + + this.enumInteger = enumInteger; + return this; + } + + /** + * Get enumInteger + * @return enumInteger + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public EnumIntegerEnum getEnumInteger() { + return enumInteger; + } + + + public void setEnumInteger(EnumIntegerEnum enumInteger) { + this.enumInteger = enumInteger; + } + + + public EnumTest enumIntegerOnly(EnumIntegerOnlyEnum enumIntegerOnly) { + + this.enumIntegerOnly = enumIntegerOnly; + return this; + } + + /** + * Get enumIntegerOnly + * @return enumIntegerOnly + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public EnumIntegerOnlyEnum getEnumIntegerOnly() { + return enumIntegerOnly; + } + + + public void setEnumIntegerOnly(EnumIntegerOnlyEnum enumIntegerOnly) { + this.enumIntegerOnly = enumIntegerOnly; + } + + + public EnumTest enumNumber(EnumNumberEnum enumNumber) { + + this.enumNumber = enumNumber; + return this; + } + + /** + * Get enumNumber + * @return enumNumber + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public EnumNumberEnum getEnumNumber() { + return enumNumber; + } + + + public void setEnumNumber(EnumNumberEnum enumNumber) { + this.enumNumber = enumNumber; + } + + + public EnumTest outerEnum(OuterEnum outerEnum) { + + this.outerEnum = outerEnum; + return this; + } + + /** + * Get outerEnum + * @return outerEnum + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public OuterEnum getOuterEnum() { + return outerEnum; + } + + + public void setOuterEnum(OuterEnum outerEnum) { + this.outerEnum = outerEnum; + } + + + public EnumTest outerEnumInteger(OuterEnumInteger outerEnumInteger) { + + this.outerEnumInteger = outerEnumInteger; + return this; + } + + /** + * Get outerEnumInteger + * @return outerEnumInteger + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public OuterEnumInteger getOuterEnumInteger() { + return outerEnumInteger; + } + + + public void setOuterEnumInteger(OuterEnumInteger outerEnumInteger) { + this.outerEnumInteger = outerEnumInteger; + } + + + public EnumTest outerEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { + + this.outerEnumDefaultValue = outerEnumDefaultValue; + return this; + } + + /** + * Get outerEnumDefaultValue + * @return outerEnumDefaultValue + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public OuterEnumDefaultValue getOuterEnumDefaultValue() { + return outerEnumDefaultValue; + } + + + public void setOuterEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { + this.outerEnumDefaultValue = outerEnumDefaultValue; + } + + + public EnumTest outerEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + return this; + } + + /** + * Get outerEnumIntegerDefaultValue + * @return outerEnumIntegerDefaultValue + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() { + return outerEnumIntegerDefaultValue; + } + + + public void setOuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { + this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumIntegerOnly, enumTest.enumIntegerOnly) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum) && + Objects.equals(this.outerEnumInteger, enumTest.outerEnumInteger) && + Objects.equals(this.outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && + Objects.equals(this.outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumStringRequired, enumInteger, enumIntegerOnly, enumNumber, outerEnum, outerEnumInteger, outerEnumDefaultValue, outerEnumIntegerDefaultValue); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EnumTest {\n"); + sb.append(" enumString: ").append(toIndentedString(enumString)).append("\n"); + sb.append(" enumStringRequired: ").append(toIndentedString(enumStringRequired)).append("\n"); + sb.append(" enumInteger: ").append(toIndentedString(enumInteger)).append("\n"); + sb.append(" enumIntegerOnly: ").append(toIndentedString(enumIntegerOnly)).append("\n"); + sb.append(" enumNumber: ").append(toIndentedString(enumNumber)).append("\n"); + sb.append(" outerEnum: ").append(toIndentedString(outerEnum)).append("\n"); + sb.append(" outerEnumInteger: ").append(toIndentedString(outerEnumInteger)).append("\n"); + sb.append(" outerEnumDefaultValue: ").append(toIndentedString(outerEnumDefaultValue)).append("\n"); + sb.append(" outerEnumIntegerDefaultValue: ").append(toIndentedString(outerEnumIntegerDefaultValue)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("enum_string"); + openapiFields.add("enum_string_required"); + openapiFields.add("enum_integer"); + openapiFields.add("enum_integer_only"); + openapiFields.add("enum_number"); + openapiFields.add("outerEnum"); + openapiFields.add("outerEnumInteger"); + openapiFields.add("outerEnumDefaultValue"); + openapiFields.add("outerEnumIntegerDefaultValue"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("enum_string_required"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!EnumTest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'EnumTest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(EnumTest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, EnumTest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public EnumTest read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!EnumTest.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `EnumTest` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : EnumTest.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EquilateralTriangle.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EquilateralTriangle.java new file mode 100644 index 00000000000..d0d2a26dab7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/EquilateralTriangle.java @@ -0,0 +1,203 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ShapeInterface; +import org.openapitools.client.model.TriangleInterface; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * EquilateralTriangle + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class EquilateralTriangle { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + private String shapeType; + + public static final String SERIALIZED_NAME_TRIANGLE_TYPE = "triangleType"; + @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) + private String triangleType; + + public EquilateralTriangle() { + } + + public EquilateralTriangle shapeType(String shapeType) { + + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getShapeType() { + return shapeType; + } + + + public void setShapeType(String shapeType) { + this.shapeType = shapeType; + } + + + public EquilateralTriangle triangleType(String triangleType) { + + this.triangleType = triangleType; + return this; + } + + /** + * Get triangleType + * @return triangleType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getTriangleType() { + return triangleType; + } + + + public void setTriangleType(String triangleType) { + this.triangleType = triangleType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EquilateralTriangle equilateralTriangle = (EquilateralTriangle) o; + return Objects.equals(this.shapeType, equilateralTriangle.shapeType) && + Objects.equals(this.triangleType, equilateralTriangle.triangleType); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, triangleType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class EquilateralTriangle {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("shapeType"); + openapiFields.add("triangleType"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("shapeType"); + openapiRequiredFields.add("triangleType"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!EquilateralTriangle.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'EquilateralTriangle' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(EquilateralTriangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, EquilateralTriangle value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public EquilateralTriangle read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!EquilateralTriangle.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `EquilateralTriangle` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : EquilateralTriangle.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java new file mode 100644 index 00000000000..9b7eb55c748 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -0,0 +1,202 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * FileSchemaTestClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class FileSchemaTestClass { + public static final String SERIALIZED_NAME_FILE = "file"; + @SerializedName(SERIALIZED_NAME_FILE) + private java.io.File file; + + public static final String SERIALIZED_NAME_FILES = "files"; + @SerializedName(SERIALIZED_NAME_FILES) + private List files = null; + + public FileSchemaTestClass() { + } + + public FileSchemaTestClass file(java.io.File file) { + + this.file = file; + return this; + } + + /** + * Get file + * @return file + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public java.io.File getFile() { + return file; + } + + + public void setFile(java.io.File file) { + this.file = file; + } + + + public FileSchemaTestClass files(List files) { + + this.files = files; + return this; + } + + public FileSchemaTestClass addFilesItem(java.io.File filesItem) { + if (this.files == null) { + this.files = new ArrayList(); + } + this.files.add(filesItem); + return this; + } + + /** + * Get files + * @return files + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getFiles() { + return files; + } + + + public void setFiles(List files) { + this.files = files; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; + return Objects.equals(this.file, fileSchemaTestClass.file) && + Objects.equals(this.files, fileSchemaTestClass.files); + } + + @Override + public int hashCode() { + return Objects.hash(file, files); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FileSchemaTestClass {\n"); + sb.append(" file: ").append(toIndentedString(file)).append("\n"); + sb.append(" files: ").append(toIndentedString(files)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("file"); + openapiFields.add("files"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FileSchemaTestClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FileSchemaTestClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(FileSchemaTestClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FileSchemaTestClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public FileSchemaTestClass read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!FileSchemaTestClass.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `FileSchemaTestClass` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Foo.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Foo.java new file mode 100644 index 00000000000..61d7be45d63 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Foo.java @@ -0,0 +1,162 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Foo + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Foo { + public static final String SERIALIZED_NAME_BAR = "bar"; + @SerializedName(SERIALIZED_NAME_BAR) + private String bar = "bar"; + + public Foo() { + } + + public Foo bar(String bar) { + + this.bar = bar; + return this; + } + + /** + * Get bar + * @return bar + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getBar() { + return bar; + } + + + public void setBar(String bar) { + this.bar = bar; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Foo foo = (Foo) o; + return Objects.equals(this.bar, foo.bar); + } + + @Override + public int hashCode() { + return Objects.hash(bar); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Foo {\n"); + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("bar"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Foo.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Foo' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Foo.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Foo value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Foo read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Foo.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Foo` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FormatTest.java new file mode 100644 index 00000000000..a5b0cbf197f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FormatTest.java @@ -0,0 +1,638 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.UUID; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * FormatTest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class FormatTest { + public static final String SERIALIZED_NAME_INTEGER = "integer"; + @SerializedName(SERIALIZED_NAME_INTEGER) + private Integer integer; + + public static final String SERIALIZED_NAME_INT32 = "int32"; + @SerializedName(SERIALIZED_NAME_INT32) + private Integer int32; + + public static final String SERIALIZED_NAME_INT64 = "int64"; + @SerializedName(SERIALIZED_NAME_INT64) + private Long int64; + + public static final String SERIALIZED_NAME_NUMBER = "number"; + @SerializedName(SERIALIZED_NAME_NUMBER) + private BigDecimal number; + + public static final String SERIALIZED_NAME_FLOAT = "float"; + @SerializedName(SERIALIZED_NAME_FLOAT) + private Float _float; + + public static final String SERIALIZED_NAME_DOUBLE = "double"; + @SerializedName(SERIALIZED_NAME_DOUBLE) + private Double _double; + + public static final String SERIALIZED_NAME_DECIMAL = "decimal"; + @SerializedName(SERIALIZED_NAME_DECIMAL) + private BigDecimal decimal; + + public static final String SERIALIZED_NAME_STRING = "string"; + @SerializedName(SERIALIZED_NAME_STRING) + private String string; + + public static final String SERIALIZED_NAME_BYTE = "byte"; + @SerializedName(SERIALIZED_NAME_BYTE) + private byte[] _byte; + + public static final String SERIALIZED_NAME_BINARY = "binary"; + @SerializedName(SERIALIZED_NAME_BINARY) + private File binary; + + public static final String SERIALIZED_NAME_DATE = "date"; + @SerializedName(SERIALIZED_NAME_DATE) + private LocalDate date; + + public static final String SERIALIZED_NAME_DATE_TIME = "dateTime"; + @SerializedName(SERIALIZED_NAME_DATE_TIME) + private OffsetDateTime dateTime; + + public static final String SERIALIZED_NAME_UUID = "uuid"; + @SerializedName(SERIALIZED_NAME_UUID) + private UUID uuid; + + public static final String SERIALIZED_NAME_PASSWORD = "password"; + @SerializedName(SERIALIZED_NAME_PASSWORD) + private String password; + + public static final String SERIALIZED_NAME_PATTERN_WITH_DIGITS = "pattern_with_digits"; + @SerializedName(SERIALIZED_NAME_PATTERN_WITH_DIGITS) + private String patternWithDigits; + + public static final String SERIALIZED_NAME_PATTERN_WITH_DIGITS_AND_DELIMITER = "pattern_with_digits_and_delimiter"; + @SerializedName(SERIALIZED_NAME_PATTERN_WITH_DIGITS_AND_DELIMITER) + private String patternWithDigitsAndDelimiter; + + public FormatTest() { + } + + public FormatTest integer(Integer integer) { + + this.integer = integer; + return this; + } + + /** + * Get integer + * minimum: 10 + * maximum: 100 + * @return integer + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Integer getInteger() { + return integer; + } + + + public void setInteger(Integer integer) { + this.integer = integer; + } + + + public FormatTest int32(Integer int32) { + + this.int32 = int32; + return this; + } + + /** + * Get int32 + * minimum: 20 + * maximum: 200 + * @return int32 + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Integer getInt32() { + return int32; + } + + + public void setInt32(Integer int32) { + this.int32 = int32; + } + + + public FormatTest int64(Long int64) { + + this.int64 = int64; + return this; + } + + /** + * Get int64 + * @return int64 + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Long getInt64() { + return int64; + } + + + public void setInt64(Long int64) { + this.int64 = int64; + } + + + public FormatTest number(BigDecimal number) { + + this.number = number; + return this; + } + + /** + * Get number + * minimum: 32.1 + * maximum: 543.2 + * @return number + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public BigDecimal getNumber() { + return number; + } + + + public void setNumber(BigDecimal number) { + this.number = number; + } + + + public FormatTest _float(Float _float) { + + this._float = _float; + return this; + } + + /** + * Get _float + * minimum: 54.3 + * maximum: 987.6 + * @return _float + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Float getFloat() { + return _float; + } + + + public void setFloat(Float _float) { + this._float = _float; + } + + + public FormatTest _double(Double _double) { + + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 67.8 + * maximum: 123.4 + * @return _double + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Double getDouble() { + return _double; + } + + + public void setDouble(Double _double) { + this._double = _double; + } + + + public FormatTest decimal(BigDecimal decimal) { + + this.decimal = decimal; + return this; + } + + /** + * Get decimal + * @return decimal + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public BigDecimal getDecimal() { + return decimal; + } + + + public void setDecimal(BigDecimal decimal) { + this.decimal = decimal; + } + + + public FormatTest string(String string) { + + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getString() { + return string; + } + + + public void setString(String string) { + this.string = string; + } + + + public FormatTest _byte(byte[] _byte) { + + this._byte = _byte; + return this; + } + + /** + * Get _byte + * @return _byte + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public byte[] getByte() { + return _byte; + } + + + public void setByte(byte[] _byte) { + this._byte = _byte; + } + + + public FormatTest binary(File binary) { + + this.binary = binary; + return this; + } + + /** + * Get binary + * @return binary + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public File getBinary() { + return binary; + } + + + public void setBinary(File binary) { + this.binary = binary; + } + + + public FormatTest date(LocalDate date) { + + this.date = date; + return this; + } + + /** + * Get date + * @return date + **/ + @javax.annotation.Nonnull + @ApiModelProperty(example = "Sun Feb 02 00:00:00 UTC 2020", required = true, value = "") + + public LocalDate getDate() { + return date; + } + + + public void setDate(LocalDate date) { + this.date = date; + } + + + public FormatTest dateTime(OffsetDateTime dateTime) { + + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @javax.annotation.Nullable + @ApiModelProperty(example = "2007-12-03T10:15:30+01:00", value = "") + + public OffsetDateTime getDateTime() { + return dateTime; + } + + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + + public FormatTest uuid(UUID uuid) { + + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @javax.annotation.Nullable + @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") + + public UUID getUuid() { + return uuid; + } + + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + + public FormatTest password(String password) { + + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getPassword() { + return password; + } + + + public void setPassword(String password) { + this.password = password; + } + + + public FormatTest patternWithDigits(String patternWithDigits) { + + this.patternWithDigits = patternWithDigits; + return this; + } + + /** + * A string that is a 10 digit number. Can have leading zeros. + * @return patternWithDigits + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "A string that is a 10 digit number. Can have leading zeros.") + + public String getPatternWithDigits() { + return patternWithDigits; + } + + + public void setPatternWithDigits(String patternWithDigits) { + this.patternWithDigits = patternWithDigits; + } + + + public FormatTest patternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { + + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + return this; + } + + /** + * A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + * @return patternWithDigitsAndDelimiter + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.") + + public String getPatternWithDigitsAndDelimiter() { + return patternWithDigitsAndDelimiter; + } + + + public void setPatternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { + this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.decimal, formatTest.decimal) && + Objects.equals(this.string, formatTest.string) && + Arrays.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password) && + Objects.equals(this.patternWithDigits, formatTest.patternWithDigits) && + Objects.equals(this.patternWithDigitsAndDelimiter, formatTest.patternWithDigitsAndDelimiter); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, decimal, string, Arrays.hashCode(_byte), binary, date, dateTime, uuid, password, patternWithDigits, patternWithDigitsAndDelimiter); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class FormatTest {\n"); + sb.append(" integer: ").append(toIndentedString(integer)).append("\n"); + sb.append(" int32: ").append(toIndentedString(int32)).append("\n"); + sb.append(" int64: ").append(toIndentedString(int64)).append("\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append(" decimal: ").append(toIndentedString(decimal)).append("\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append(" _byte: ").append(toIndentedString(_byte)).append("\n"); + sb.append(" binary: ").append(toIndentedString(binary)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); + sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("integer"); + openapiFields.add("int32"); + openapiFields.add("int64"); + openapiFields.add("number"); + openapiFields.add("float"); + openapiFields.add("double"); + openapiFields.add("decimal"); + openapiFields.add("string"); + openapiFields.add("byte"); + openapiFields.add("binary"); + openapiFields.add("date"); + openapiFields.add("dateTime"); + openapiFields.add("uuid"); + openapiFields.add("password"); + openapiFields.add("pattern_with_digits"); + openapiFields.add("pattern_with_digits_and_delimiter"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("number"); + openapiRequiredFields.add("byte"); + openapiRequiredFields.add("date"); + openapiRequiredFields.add("password"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FormatTest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FormatTest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(FormatTest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FormatTest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public FormatTest read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!FormatTest.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `FormatTest` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : FormatTest.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Fruit.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Fruit.java new file mode 100644 index 00000000000..6f907a92f0a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Fruit.java @@ -0,0 +1,221 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.openapitools.client.model.Apple; +import org.openapitools.client.model.Banana; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Fruit extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Fruit.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Fruit.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Fruit' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterApple = gson.getDelegateAdapter(this, TypeToken.get(Apple.class)); + final TypeAdapter adapterBanana = gson.getDelegateAdapter(this, TypeToken.get(Banana.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Fruit value) throws IOException { + // check if the actual instance is of the type `Apple` + if (value.getActualInstance() instanceof Apple) { + JsonObject obj = adapterApple.toJsonTree((Apple)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `Banana` + if (value.getActualInstance() instanceof Banana) { + JsonObject obj = adapterBanana.toJsonTree((Banana)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Apple, Banana"); + } + + @Override + public Fruit read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + + // deserialize Apple + try { + deserialized = adapterApple.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Apple'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Apple'", e); + } + + // deserialize Banana + try { + deserialized = adapterBanana.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Banana'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Banana'", e); + } + + if (match == 1) { + Fruit ret = new Fruit(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Fruit: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public Fruit() { + super("oneOf", Boolean.FALSE); + } + + public Fruit(Apple o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Fruit(Banana o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Apple", new GenericType() { + }); + schemas.put("Banana", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return Fruit.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Apple, Banana + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof Apple) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Banana) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Apple, Banana"); + } + + /** + * Get the actual instance, which can be the following: + * Apple, Banana + * + * @return The actual instance (Apple, Banana) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Apple`. If the actual instance is not `Apple`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Apple` + * @throws ClassCastException if the instance is not `Apple` + */ + public Apple getApple() throws ClassCastException { + return (Apple)super.getActualInstance(); + } + + /** + * Get the actual instance of `Banana`. If the actual instance is not `Banana`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Banana` + * @throws ClassCastException if the instance is not `Banana` + */ + public Banana getBanana() throws ClassCastException { + return (Banana)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FruitReq.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FruitReq.java new file mode 100644 index 00000000000..303049b6007 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/FruitReq.java @@ -0,0 +1,226 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.openapitools.client.model.AppleReq; +import org.openapitools.client.model.BananaReq; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class FruitReq extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(FruitReq.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!FruitReq.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'FruitReq' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterAppleReq = gson.getDelegateAdapter(this, TypeToken.get(AppleReq.class)); + final TypeAdapter adapterBananaReq = gson.getDelegateAdapter(this, TypeToken.get(BananaReq.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, FruitReq value) throws IOException { + // check if the actual instance is of the type `AppleReq` + if (value.getActualInstance() instanceof AppleReq) { + JsonObject obj = adapterAppleReq.toJsonTree((AppleReq)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `BananaReq` + if (value.getActualInstance() instanceof BananaReq) { + JsonObject obj = adapterBananaReq.toJsonTree((BananaReq)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: AppleReq, BananaReq"); + } + + @Override + public FruitReq read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + + // deserialize AppleReq + try { + deserialized = adapterAppleReq.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'AppleReq'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'AppleReq'", e); + } + + // deserialize BananaReq + try { + deserialized = adapterBananaReq.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'BananaReq'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'BananaReq'", e); + } + + if (match == 1) { + FruitReq ret = new FruitReq(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for FruitReq: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public FruitReq() { + super("oneOf", Boolean.TRUE); + } + + public FruitReq(AppleReq o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + public FruitReq(BananaReq o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + static { + schemas.put("AppleReq", new GenericType() { + }); + schemas.put("BananaReq", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return FruitReq.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * AppleReq, BananaReq + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance == null) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof AppleReq) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof BananaReq) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be AppleReq, BananaReq"); + } + + /** + * Get the actual instance, which can be the following: + * AppleReq, BananaReq + * + * @return The actual instance (AppleReq, BananaReq) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `AppleReq`. If the actual instance is not `AppleReq`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `AppleReq` + * @throws ClassCastException if the instance is not `AppleReq` + */ + public AppleReq getAppleReq() throws ClassCastException { + return (AppleReq)super.getActualInstance(); + } + + /** + * Get the actual instance of `BananaReq`. If the actual instance is not `BananaReq`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `BananaReq` + * @throws ClassCastException if the instance is not `BananaReq` + */ + public BananaReq getBananaReq() throws ClassCastException { + return (BananaReq)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GmFruit.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GmFruit.java new file mode 100644 index 00000000000..441f0330de6 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GmFruit.java @@ -0,0 +1,216 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.openapitools.client.model.Apple; +import org.openapitools.client.model.Banana; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class GmFruit extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(GmFruit.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!GmFruit.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'GmFruit' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterApple = gson.getDelegateAdapter(this, TypeToken.get(Apple.class)); + final TypeAdapter adapterBanana = gson.getDelegateAdapter(this, TypeToken.get(Banana.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, GmFruit value) throws IOException { + // check if the actual instance is of the type `Apple` + if (value.getActualInstance() instanceof Apple) { + JsonObject obj = adapterApple.toJsonTree((Apple)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `Banana` + if (value.getActualInstance() instanceof Banana) { + JsonObject obj = adapterBanana.toJsonTree((Banana)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match anyOf schemas: Apple, Banana"); + } + + @Override + public GmFruit read(JsonReader in) throws IOException { + Object deserialized = null; + + // deserialize Apple + try { + deserialized = gson.fromJson(in, Apple.class); + log.log(Level.FINER, "Input data matches schema 'Apple'"); + GmFruit ret = new GmFruit(); + ret.setActualInstance(deserialized); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Apple'", e); + } + + // deserialize Banana + try { + deserialized = gson.fromJson(in, Banana.class); + log.log(Level.FINER, "Input data matches schema 'Banana'"); + GmFruit ret = new GmFruit(); + ret.setActualInstance(deserialized); + return ret; + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Banana'", e); + } + + throw new IOException("Failed deserialization for GmFruit: no match found."); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in anyOf + public static final Map schemas = new HashMap(); + + public GmFruit() { + super("anyOf", Boolean.FALSE); + } + + public GmFruit(Apple o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public GmFruit(Banana o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Apple", new GenericType() { + }); + schemas.put("Banana", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return GmFruit.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * Apple, Banana + * + * It could be an instance of the 'anyOf' schemas. + * The anyOf child schemas may themselves be a composed schema (allOf, anyOf, anyOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof Apple) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Banana) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Apple, Banana"); + } + + /** + * Get the actual instance, which can be the following: + * Apple, Banana + * + * @return The actual instance (Apple, Banana) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Apple`. If the actual instance is not `Apple`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Apple` + * @throws ClassCastException if the instance is not `Apple` + */ + public Apple getApple() throws ClassCastException { + return (Apple)super.getActualInstance(); + } + + /** + * Get the actual instance of `Banana`. If the actual instance is not `Banana`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Banana` + * @throws ClassCastException if the instance is not `Banana` + */ + public Banana getBanana() throws ClassCastException { + return (Banana)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java new file mode 100644 index 00000000000..df924fe5f33 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java @@ -0,0 +1,172 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ParentPet; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * GrandparentAnimal + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class GrandparentAnimal { + public static final String SERIALIZED_NAME_PET_TYPE = "pet_type"; + @SerializedName(SERIALIZED_NAME_PET_TYPE) + protected String petType; + + public GrandparentAnimal() { + this.petType = this.getClass().getSimpleName(); + } + + public GrandparentAnimal petType(String petType) { + + this.petType = petType; + return this; + } + + /** + * Get petType + * @return petType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getPetType() { + return petType; + } + + + public void setPetType(String petType) { + this.petType = petType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + GrandparentAnimal grandparentAnimal = (GrandparentAnimal) o; + return Objects.equals(this.petType, grandparentAnimal.petType); + } + + @Override + public int hashCode() { + return Objects.hash(petType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class GrandparentAnimal {\n"); + sb.append(" petType: ").append(toIndentedString(petType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("pet_type"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("pet_type"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!GrandparentAnimal.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'GrandparentAnimal' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(GrandparentAnimal.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, GrandparentAnimal value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public GrandparentAnimal read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!GrandparentAnimal.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `GrandparentAnimal` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : GrandparentAnimal.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java new file mode 100644 index 00000000000..31a4a05a3d5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -0,0 +1,184 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * HasOnlyReadOnly + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HasOnlyReadOnly { + public static final String SERIALIZED_NAME_BAR = "bar"; + @SerializedName(SERIALIZED_NAME_BAR) + private String bar; + + public static final String SERIALIZED_NAME_FOO = "foo"; + @SerializedName(SERIALIZED_NAME_FOO) + private String foo; + + public HasOnlyReadOnly() { + } + + + public HasOnlyReadOnly( + String bar, + String foo + ) { + this(); + this.bar = bar; + this.foo = foo; + } + + /** + * Get bar + * @return bar + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getBar() { + return bar; + } + + + + + /** + * Get foo + * @return foo + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getFoo() { + return foo; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HasOnlyReadOnly {\n"); + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" foo: ").append(toIndentedString(foo)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("bar"); + openapiFields.add("foo"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!HasOnlyReadOnly.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'HasOnlyReadOnly' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(HasOnlyReadOnly.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, HasOnlyReadOnly value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public HasOnlyReadOnly read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!HasOnlyReadOnly.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `HasOnlyReadOnly` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/HealthCheckResult.java new file mode 100644 index 00000000000..8af6fca3706 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -0,0 +1,175 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.jackson.nullable.JsonNullable; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + */ +@ApiModel(description = "Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model.") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HealthCheckResult { + public static final String SERIALIZED_NAME_NULLABLE_MESSAGE = "NullableMessage"; + @SerializedName(SERIALIZED_NAME_NULLABLE_MESSAGE) + private String nullableMessage; + + public HealthCheckResult() { + } + + public HealthCheckResult nullableMessage(String nullableMessage) { + + this.nullableMessage = nullableMessage; + return this; + } + + /** + * Get nullableMessage + * @return nullableMessage + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getNullableMessage() { + return nullableMessage; + } + + + public void setNullableMessage(String nullableMessage) { + this.nullableMessage = nullableMessage; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HealthCheckResult healthCheckResult = (HealthCheckResult) o; + return Objects.equals(this.nullableMessage, healthCheckResult.nullableMessage); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(nullableMessage); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class HealthCheckResult {\n"); + sb.append(" nullableMessage: ").append(toIndentedString(nullableMessage)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("NullableMessage"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!HealthCheckResult.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'HealthCheckResult' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(HealthCheckResult.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, HealthCheckResult value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public HealthCheckResult read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!HealthCheckResult.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `HealthCheckResult` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/InlineResponseDefault.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/InlineResponseDefault.java new file mode 100644 index 00000000000..925d6c646c9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/InlineResponseDefault.java @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Foo; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * InlineResponseDefault + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class InlineResponseDefault { + public static final String SERIALIZED_NAME_STRING = "string"; + @SerializedName(SERIALIZED_NAME_STRING) + private Foo string; + + public InlineResponseDefault() { + } + + public InlineResponseDefault string(Foo string) { + + this.string = string; + return this; + } + + /** + * Get string + * @return string + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Foo getString() { + return string; + } + + + public void setString(Foo string) { + this.string = string; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + InlineResponseDefault inlineResponseDefault = (InlineResponseDefault) o; + return Objects.equals(this.string, inlineResponseDefault.string); + } + + @Override + public int hashCode() { + return Objects.hash(string); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class InlineResponseDefault {\n"); + sb.append(" string: ").append(toIndentedString(string)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("string"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!InlineResponseDefault.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'InlineResponseDefault' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(InlineResponseDefault.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, InlineResponseDefault value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public InlineResponseDefault read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!InlineResponseDefault.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `InlineResponseDefault` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java new file mode 100644 index 00000000000..2c2a4456551 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java @@ -0,0 +1,203 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ShapeInterface; +import org.openapitools.client.model.TriangleInterface; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * IsoscelesTriangle + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class IsoscelesTriangle { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + private String shapeType; + + public static final String SERIALIZED_NAME_TRIANGLE_TYPE = "triangleType"; + @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) + private String triangleType; + + public IsoscelesTriangle() { + } + + public IsoscelesTriangle shapeType(String shapeType) { + + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getShapeType() { + return shapeType; + } + + + public void setShapeType(String shapeType) { + this.shapeType = shapeType; + } + + + public IsoscelesTriangle triangleType(String triangleType) { + + this.triangleType = triangleType; + return this; + } + + /** + * Get triangleType + * @return triangleType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getTriangleType() { + return triangleType; + } + + + public void setTriangleType(String triangleType) { + this.triangleType = triangleType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + IsoscelesTriangle isoscelesTriangle = (IsoscelesTriangle) o; + return Objects.equals(this.shapeType, isoscelesTriangle.shapeType) && + Objects.equals(this.triangleType, isoscelesTriangle.triangleType); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, triangleType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class IsoscelesTriangle {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("shapeType"); + openapiFields.add("triangleType"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("shapeType"); + openapiRequiredFields.add("triangleType"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!IsoscelesTriangle.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'IsoscelesTriangle' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(IsoscelesTriangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, IsoscelesTriangle value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public IsoscelesTriangle read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!IsoscelesTriangle.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `IsoscelesTriangle` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : IsoscelesTriangle.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Mammal.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Mammal.java new file mode 100644 index 00000000000..466644f4b7c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Mammal.java @@ -0,0 +1,261 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Pig; +import org.openapitools.client.model.Whale; +import org.openapitools.client.model.Zebra; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Mammal extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Mammal.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Mammal.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Mammal' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterPig = gson.getDelegateAdapter(this, TypeToken.get(Pig.class)); + final TypeAdapter adapterWhale = gson.getDelegateAdapter(this, TypeToken.get(Whale.class)); + final TypeAdapter adapterZebra = gson.getDelegateAdapter(this, TypeToken.get(Zebra.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Mammal value) throws IOException { + // check if the actual instance is of the type `Pig` + if (value.getActualInstance() instanceof Pig) { + JsonObject obj = adapterPig.toJsonTree((Pig)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `Whale` + if (value.getActualInstance() instanceof Whale) { + JsonObject obj = adapterWhale.toJsonTree((Whale)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `Zebra` + if (value.getActualInstance() instanceof Zebra) { + JsonObject obj = adapterZebra.toJsonTree((Zebra)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Pig, Whale, Zebra"); + } + + @Override + public Mammal read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + + // deserialize Pig + try { + deserialized = adapterPig.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Pig'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Pig'", e); + } + + // deserialize Whale + try { + deserialized = adapterWhale.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Whale'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Whale'", e); + } + + // deserialize Zebra + try { + deserialized = adapterZebra.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Zebra'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Zebra'", e); + } + + if (match == 1) { + Mammal ret = new Mammal(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Mammal: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public Mammal() { + super("oneOf", Boolean.FALSE); + } + + public Mammal(Pig o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Mammal(Whale o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Mammal(Zebra o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Pig", new GenericType() { + }); + schemas.put("Whale", new GenericType() { + }); + schemas.put("Zebra", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return Mammal.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Pig, Whale, Zebra + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof Pig) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Whale) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Zebra) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Pig, Whale, Zebra"); + } + + /** + * Get the actual instance, which can be the following: + * Pig, Whale, Zebra + * + * @return The actual instance (Pig, Whale, Zebra) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Pig`. If the actual instance is not `Pig`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Pig` + * @throws ClassCastException if the instance is not `Pig` + */ + public Pig getPig() throws ClassCastException { + return (Pig)super.getActualInstance(); + } + + /** + * Get the actual instance of `Whale`. If the actual instance is not `Whale`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Whale` + * @throws ClassCastException if the instance is not `Whale` + */ + public Whale getWhale() throws ClassCastException { + return (Whale)super.getActualInstance(); + } + + /** + * Get the actual instance of `Zebra`. If the actual instance is not `Zebra`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Zebra` + * @throws ClassCastException if the instance is not `Zebra` + */ + public Zebra getZebra() throws ClassCastException { + return (Zebra)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/MapTest.java new file mode 100644 index 00000000000..615d6de3535 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/MapTest.java @@ -0,0 +1,334 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * MapTest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class MapTest { + public static final String SERIALIZED_NAME_MAP_MAP_OF_STRING = "map_map_of_string"; + @SerializedName(SERIALIZED_NAME_MAP_MAP_OF_STRING) + private Map> mapMapOfString = null; + + /** + * Gets or Sets inner + */ + @JsonAdapter(InnerEnum.Adapter.class) + public enum InnerEnum { + UPPER("UPPER"), + + LOWER("lower"); + + private String value; + + InnerEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static InnerEnum fromValue(String value) { + for (InnerEnum b : InnerEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final InnerEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public InnerEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return InnerEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_MAP_OF_ENUM_STRING = "map_of_enum_string"; + @SerializedName(SERIALIZED_NAME_MAP_OF_ENUM_STRING) + private Map mapOfEnumString = null; + + public static final String SERIALIZED_NAME_DIRECT_MAP = "direct_map"; + @SerializedName(SERIALIZED_NAME_DIRECT_MAP) + private Map directMap = null; + + public static final String SERIALIZED_NAME_INDIRECT_MAP = "indirect_map"; + @SerializedName(SERIALIZED_NAME_INDIRECT_MAP) + private Map indirectMap = null; + + public MapTest() { + } + + public MapTest mapMapOfString(Map> mapMapOfString) { + + this.mapMapOfString = mapMapOfString; + return this; + } + + public MapTest putMapMapOfStringItem(String key, Map mapMapOfStringItem) { + if (this.mapMapOfString == null) { + this.mapMapOfString = new HashMap>(); + } + this.mapMapOfString.put(key, mapMapOfStringItem); + return this; + } + + /** + * Get mapMapOfString + * @return mapMapOfString + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map> getMapMapOfString() { + return mapMapOfString; + } + + + public void setMapMapOfString(Map> mapMapOfString) { + this.mapMapOfString = mapMapOfString; + } + + + public MapTest mapOfEnumString(Map mapOfEnumString) { + + this.mapOfEnumString = mapOfEnumString; + return this; + } + + public MapTest putMapOfEnumStringItem(String key, InnerEnum mapOfEnumStringItem) { + if (this.mapOfEnumString == null) { + this.mapOfEnumString = new HashMap(); + } + this.mapOfEnumString.put(key, mapOfEnumStringItem); + return this; + } + + /** + * Get mapOfEnumString + * @return mapOfEnumString + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getMapOfEnumString() { + return mapOfEnumString; + } + + + public void setMapOfEnumString(Map mapOfEnumString) { + this.mapOfEnumString = mapOfEnumString; + } + + + public MapTest directMap(Map directMap) { + + this.directMap = directMap; + return this; + } + + public MapTest putDirectMapItem(String key, Boolean directMapItem) { + if (this.directMap == null) { + this.directMap = new HashMap(); + } + this.directMap.put(key, directMapItem); + return this; + } + + /** + * Get directMap + * @return directMap + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getDirectMap() { + return directMap; + } + + + public void setDirectMap(Map directMap) { + this.directMap = directMap; + } + + + public MapTest indirectMap(Map indirectMap) { + + this.indirectMap = indirectMap; + return this; + } + + public MapTest putIndirectMapItem(String key, Boolean indirectMapItem) { + if (this.indirectMap == null) { + this.indirectMap = new HashMap(); + } + this.indirectMap.put(key, indirectMapItem); + return this; + } + + /** + * Get indirectMap + * @return indirectMap + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getIndirectMap() { + return indirectMap; + } + + + public void setIndirectMap(Map indirectMap) { + this.indirectMap = indirectMap; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(this.directMap, mapTest.directMap) && + Objects.equals(this.indirectMap, mapTest.indirectMap); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString, directMap, indirectMap); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MapTest {\n"); + sb.append(" mapMapOfString: ").append(toIndentedString(mapMapOfString)).append("\n"); + sb.append(" mapOfEnumString: ").append(toIndentedString(mapOfEnumString)).append("\n"); + sb.append(" directMap: ").append(toIndentedString(directMap)).append("\n"); + sb.append(" indirectMap: ").append(toIndentedString(indirectMap)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("map_map_of_string"); + openapiFields.add("map_of_enum_string"); + openapiFields.add("direct_map"); + openapiFields.add("indirect_map"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!MapTest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'MapTest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(MapTest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, MapTest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public MapTest read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!MapTest.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `MapTest` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java new file mode 100644 index 00000000000..ae6e2282c9f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -0,0 +1,236 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.openapitools.client.model.Animal; +import org.threeten.bp.OffsetDateTime; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * MixedPropertiesAndAdditionalPropertiesClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class MixedPropertiesAndAdditionalPropertiesClass { + public static final String SERIALIZED_NAME_UUID = "uuid"; + @SerializedName(SERIALIZED_NAME_UUID) + private UUID uuid; + + public static final String SERIALIZED_NAME_DATE_TIME = "dateTime"; + @SerializedName(SERIALIZED_NAME_DATE_TIME) + private OffsetDateTime dateTime; + + public static final String SERIALIZED_NAME_MAP = "map"; + @SerializedName(SERIALIZED_NAME_MAP) + private Map map = null; + + public MixedPropertiesAndAdditionalPropertiesClass() { + } + + public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { + + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public UUID getUuid() { + return uuid; + } + + + public void setUuid(UUID uuid) { + this.uuid = uuid; + } + + + public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { + + this.dateTime = dateTime; + return this; + } + + /** + * Get dateTime + * @return dateTime + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public OffsetDateTime getDateTime() { + return dateTime; + } + + + public void setDateTime(OffsetDateTime dateTime) { + this.dateTime = dateTime; + } + + + public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { + + this.map = map; + return this; + } + + public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal mapItem) { + if (this.map == null) { + this.map = new HashMap(); + } + this.map.put(key, mapItem); + return this; + } + + /** + * Get map + * @return map + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getMap() { + return map; + } + + + public void setMap(Map map) { + this.map = map; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class MixedPropertiesAndAdditionalPropertiesClass {\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); + sb.append(" map: ").append(toIndentedString(map)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("uuid"); + openapiFields.add("dateTime"); + openapiFields.add("map"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!MixedPropertiesAndAdditionalPropertiesClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'MixedPropertiesAndAdditionalPropertiesClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(MixedPropertiesAndAdditionalPropertiesClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, MixedPropertiesAndAdditionalPropertiesClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public MixedPropertiesAndAdditionalPropertiesClass read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!MixedPropertiesAndAdditionalPropertiesClass.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `MixedPropertiesAndAdditionalPropertiesClass` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Model200Response.java new file mode 100644 index 00000000000..b9ec6bd483d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Model200Response.java @@ -0,0 +1,193 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Model for testing model name starting with number + */ +@ApiModel(description = "Model for testing model name starting with number") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Model200Response { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + private Integer name; + + public static final String SERIALIZED_NAME_PROPERTY_CLASS = "class"; + @SerializedName(SERIALIZED_NAME_PROPERTY_CLASS) + private String propertyClass; + + public Model200Response() { + } + + public Model200Response name(Integer name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Integer getName() { + return name; + } + + + public void setName(Integer name) { + this.name = name; + } + + + public Model200Response propertyClass(String propertyClass) { + + this.propertyClass = propertyClass; + return this; + } + + /** + * Get propertyClass + * @return propertyClass + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getPropertyClass() { + return propertyClass; + } + + + public void setPropertyClass(String propertyClass) { + this.propertyClass = propertyClass; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200response = (Model200Response) o; + return Objects.equals(this.name, _200response.name) && + Objects.equals(this.propertyClass, _200response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Model200Response {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("name"); + openapiFields.add("class"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Model200Response.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Model200Response' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Model200Response.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Model200Response value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Model200Response read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Model200Response.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Model200Response` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ModelApiResponse.java new file mode 100644 index 00000000000..c9f691d6458 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -0,0 +1,222 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ModelApiResponse + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ModelApiResponse { + public static final String SERIALIZED_NAME_CODE = "code"; + @SerializedName(SERIALIZED_NAME_CODE) + private Integer code; + + public static final String SERIALIZED_NAME_TYPE = "type"; + @SerializedName(SERIALIZED_NAME_TYPE) + private String type; + + public static final String SERIALIZED_NAME_MESSAGE = "message"; + @SerializedName(SERIALIZED_NAME_MESSAGE) + private String message; + + public ModelApiResponse() { + } + + public ModelApiResponse code(Integer code) { + + this.code = code; + return this; + } + + /** + * Get code + * @return code + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Integer getCode() { + return code; + } + + + public void setCode(Integer code) { + this.code = code; + } + + + public ModelApiResponse type(String type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getType() { + return type; + } + + + public void setType(String type) { + this.type = type; + } + + + public ModelApiResponse message(String message) { + + this.message = message; + return this; + } + + /** + * Get message + * @return message + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getMessage() { + return message; + } + + + public void setMessage(String message) { + this.message = message; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("code"); + openapiFields.add("type"); + openapiFields.add("message"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ModelApiResponse.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ModelApiResponse' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ModelApiResponse.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ModelApiResponse value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ModelApiResponse read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ModelApiResponse.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ModelApiResponse` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ModelReturn.java new file mode 100644 index 00000000000..64aadfb6a82 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Model for testing reserved words + */ +@ApiModel(description = "Model for testing reserved words") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ModelReturn { + public static final String SERIALIZED_NAME_RETURN = "return"; + @SerializedName(SERIALIZED_NAME_RETURN) + private Integer _return; + + public ModelReturn() { + } + + public ModelReturn _return(Integer _return) { + + this._return = _return; + return this; + } + + /** + * Get _return + * @return _return + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Integer getReturn() { + return _return; + } + + + public void setReturn(Integer _return) { + this._return = _return; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(this._return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelReturn {\n"); + sb.append(" _return: ").append(toIndentedString(_return)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("return"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ModelReturn.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ModelReturn' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ModelReturn.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ModelReturn value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ModelReturn read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ModelReturn.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ModelReturn` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Name.java new file mode 100644 index 00000000000..528c159a8f3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Name.java @@ -0,0 +1,253 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Model for testing model name same as property name + */ +@ApiModel(description = "Model for testing model name same as property name") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Name { + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + private Integer name; + + public static final String SERIALIZED_NAME_SNAKE_CASE = "snake_case"; + @SerializedName(SERIALIZED_NAME_SNAKE_CASE) + private Integer snakeCase; + + public static final String SERIALIZED_NAME_PROPERTY = "property"; + @SerializedName(SERIALIZED_NAME_PROPERTY) + private String property; + + public static final String SERIALIZED_NAME_123NUMBER = "123Number"; + @SerializedName(SERIALIZED_NAME_123NUMBER) + private Integer _123number; + + public Name() { + } + + + public Name( + Integer snakeCase, + Integer _123number + ) { + this(); + this.snakeCase = snakeCase; + this._123number = _123number; + } + + public Name name(Integer name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public Integer getName() { + return name; + } + + + public void setName(Integer name) { + this.name = name; + } + + + /** + * Get snakeCase + * @return snakeCase + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Integer getSnakeCase() { + return snakeCase; + } + + + + + public Name property(String property) { + + this.property = property; + return this; + } + + /** + * Get property + * @return property + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getProperty() { + return property; + } + + + public void setProperty(String property) { + this.property = property; + } + + + /** + * Get _123number + * @return _123number + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Integer get123number() { + return _123number; + } + + + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123number, name._123number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123number); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Name {\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" snakeCase: ").append(toIndentedString(snakeCase)).append("\n"); + sb.append(" property: ").append(toIndentedString(property)).append("\n"); + sb.append(" _123number: ").append(toIndentedString(_123number)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("name"); + openapiFields.add("snake_case"); + openapiFields.add("property"); + openapiFields.add("123Number"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("name"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Name.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Name' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Name.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Name value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Name read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Name.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Name` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Name.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NullableClass.java new file mode 100644 index 00000000000..5aa141fee0a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NullableClass.java @@ -0,0 +1,561 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * NullableClass + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class NullableClass extends HashMap { + public static final String SERIALIZED_NAME_INTEGER_PROP = "integer_prop"; + @SerializedName(SERIALIZED_NAME_INTEGER_PROP) + private Integer integerProp; + + public static final String SERIALIZED_NAME_NUMBER_PROP = "number_prop"; + @SerializedName(SERIALIZED_NAME_NUMBER_PROP) + private BigDecimal numberProp; + + public static final String SERIALIZED_NAME_BOOLEAN_PROP = "boolean_prop"; + @SerializedName(SERIALIZED_NAME_BOOLEAN_PROP) + private Boolean booleanProp; + + public static final String SERIALIZED_NAME_STRING_PROP = "string_prop"; + @SerializedName(SERIALIZED_NAME_STRING_PROP) + private String stringProp; + + public static final String SERIALIZED_NAME_DATE_PROP = "date_prop"; + @SerializedName(SERIALIZED_NAME_DATE_PROP) + private LocalDate dateProp; + + public static final String SERIALIZED_NAME_DATETIME_PROP = "datetime_prop"; + @SerializedName(SERIALIZED_NAME_DATETIME_PROP) + private OffsetDateTime datetimeProp; + + public static final String SERIALIZED_NAME_ARRAY_NULLABLE_PROP = "array_nullable_prop"; + @SerializedName(SERIALIZED_NAME_ARRAY_NULLABLE_PROP) + private List arrayNullableProp = null; + + public static final String SERIALIZED_NAME_ARRAY_AND_ITEMS_NULLABLE_PROP = "array_and_items_nullable_prop"; + @SerializedName(SERIALIZED_NAME_ARRAY_AND_ITEMS_NULLABLE_PROP) + private List arrayAndItemsNullableProp = null; + + public static final String SERIALIZED_NAME_ARRAY_ITEMS_NULLABLE = "array_items_nullable"; + @SerializedName(SERIALIZED_NAME_ARRAY_ITEMS_NULLABLE) + private List arrayItemsNullable = null; + + public static final String SERIALIZED_NAME_OBJECT_NULLABLE_PROP = "object_nullable_prop"; + @SerializedName(SERIALIZED_NAME_OBJECT_NULLABLE_PROP) + private Map objectNullableProp = null; + + public static final String SERIALIZED_NAME_OBJECT_AND_ITEMS_NULLABLE_PROP = "object_and_items_nullable_prop"; + @SerializedName(SERIALIZED_NAME_OBJECT_AND_ITEMS_NULLABLE_PROP) + private Map objectAndItemsNullableProp = null; + + public static final String SERIALIZED_NAME_OBJECT_ITEMS_NULLABLE = "object_items_nullable"; + @SerializedName(SERIALIZED_NAME_OBJECT_ITEMS_NULLABLE) + private Map objectItemsNullable = null; + + public NullableClass() { + } + + public NullableClass integerProp(Integer integerProp) { + + this.integerProp = integerProp; + return this; + } + + /** + * Get integerProp + * @return integerProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Integer getIntegerProp() { + return integerProp; + } + + + public void setIntegerProp(Integer integerProp) { + this.integerProp = integerProp; + } + + + public NullableClass numberProp(BigDecimal numberProp) { + + this.numberProp = numberProp; + return this; + } + + /** + * Get numberProp + * @return numberProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public BigDecimal getNumberProp() { + return numberProp; + } + + + public void setNumberProp(BigDecimal numberProp) { + this.numberProp = numberProp; + } + + + public NullableClass booleanProp(Boolean booleanProp) { + + this.booleanProp = booleanProp; + return this; + } + + /** + * Get booleanProp + * @return booleanProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Boolean getBooleanProp() { + return booleanProp; + } + + + public void setBooleanProp(Boolean booleanProp) { + this.booleanProp = booleanProp; + } + + + public NullableClass stringProp(String stringProp) { + + this.stringProp = stringProp; + return this; + } + + /** + * Get stringProp + * @return stringProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getStringProp() { + return stringProp; + } + + + public void setStringProp(String stringProp) { + this.stringProp = stringProp; + } + + + public NullableClass dateProp(LocalDate dateProp) { + + this.dateProp = dateProp; + return this; + } + + /** + * Get dateProp + * @return dateProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public LocalDate getDateProp() { + return dateProp; + } + + + public void setDateProp(LocalDate dateProp) { + this.dateProp = dateProp; + } + + + public NullableClass datetimeProp(OffsetDateTime datetimeProp) { + + this.datetimeProp = datetimeProp; + return this; + } + + /** + * Get datetimeProp + * @return datetimeProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public OffsetDateTime getDatetimeProp() { + return datetimeProp; + } + + + public void setDatetimeProp(OffsetDateTime datetimeProp) { + this.datetimeProp = datetimeProp; + } + + + public NullableClass arrayNullableProp(List arrayNullableProp) { + + this.arrayNullableProp = arrayNullableProp; + return this; + } + + public NullableClass addArrayNullablePropItem(Object arrayNullablePropItem) { + if (this.arrayNullableProp == null) { + this.arrayNullableProp = new ArrayList(); + } + this.arrayNullableProp.add(arrayNullablePropItem); + return this; + } + + /** + * Get arrayNullableProp + * @return arrayNullableProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getArrayNullableProp() { + return arrayNullableProp; + } + + + public void setArrayNullableProp(List arrayNullableProp) { + this.arrayNullableProp = arrayNullableProp; + } + + + public NullableClass arrayAndItemsNullableProp(List arrayAndItemsNullableProp) { + + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + return this; + } + + public NullableClass addArrayAndItemsNullablePropItem(Object arrayAndItemsNullablePropItem) { + if (this.arrayAndItemsNullableProp == null) { + this.arrayAndItemsNullableProp = new ArrayList(); + } + this.arrayAndItemsNullableProp.add(arrayAndItemsNullablePropItem); + return this; + } + + /** + * Get arrayAndItemsNullableProp + * @return arrayAndItemsNullableProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getArrayAndItemsNullableProp() { + return arrayAndItemsNullableProp; + } + + + public void setArrayAndItemsNullableProp(List arrayAndItemsNullableProp) { + this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; + } + + + public NullableClass arrayItemsNullable(List arrayItemsNullable) { + + this.arrayItemsNullable = arrayItemsNullable; + return this; + } + + public NullableClass addArrayItemsNullableItem(Object arrayItemsNullableItem) { + if (this.arrayItemsNullable == null) { + this.arrayItemsNullable = new ArrayList(); + } + this.arrayItemsNullable.add(arrayItemsNullableItem); + return this; + } + + /** + * Get arrayItemsNullable + * @return arrayItemsNullable + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getArrayItemsNullable() { + return arrayItemsNullable; + } + + + public void setArrayItemsNullable(List arrayItemsNullable) { + this.arrayItemsNullable = arrayItemsNullable; + } + + + public NullableClass objectNullableProp(Map objectNullableProp) { + + this.objectNullableProp = objectNullableProp; + return this; + } + + public NullableClass putObjectNullablePropItem(String key, Object objectNullablePropItem) { + if (this.objectNullableProp == null) { + this.objectNullableProp = new HashMap(); + } + this.objectNullableProp.put(key, objectNullablePropItem); + return this; + } + + /** + * Get objectNullableProp + * @return objectNullableProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getObjectNullableProp() { + return objectNullableProp; + } + + + public void setObjectNullableProp(Map objectNullableProp) { + this.objectNullableProp = objectNullableProp; + } + + + public NullableClass objectAndItemsNullableProp(Map objectAndItemsNullableProp) { + + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + return this; + } + + public NullableClass putObjectAndItemsNullablePropItem(String key, Object objectAndItemsNullablePropItem) { + if (this.objectAndItemsNullableProp == null) { + this.objectAndItemsNullableProp = new HashMap(); + } + this.objectAndItemsNullableProp.put(key, objectAndItemsNullablePropItem); + return this; + } + + /** + * Get objectAndItemsNullableProp + * @return objectAndItemsNullableProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getObjectAndItemsNullableProp() { + return objectAndItemsNullableProp; + } + + + public void setObjectAndItemsNullableProp(Map objectAndItemsNullableProp) { + this.objectAndItemsNullableProp = objectAndItemsNullableProp; + } + + + public NullableClass objectItemsNullable(Map objectItemsNullable) { + + this.objectItemsNullable = objectItemsNullable; + return this; + } + + public NullableClass putObjectItemsNullableItem(String key, Object objectItemsNullableItem) { + if (this.objectItemsNullable == null) { + this.objectItemsNullable = new HashMap(); + } + this.objectItemsNullable.put(key, objectItemsNullableItem); + return this; + } + + /** + * Get objectItemsNullable + * @return objectItemsNullable + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Map getObjectItemsNullable() { + return objectItemsNullable; + } + + + public void setObjectItemsNullable(Map objectItemsNullable) { + this.objectItemsNullable = objectItemsNullable; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NullableClass nullableClass = (NullableClass) o; + return Objects.equals(this.integerProp, nullableClass.integerProp) && + Objects.equals(this.numberProp, nullableClass.numberProp) && + Objects.equals(this.booleanProp, nullableClass.booleanProp) && + Objects.equals(this.stringProp, nullableClass.stringProp) && + Objects.equals(this.dateProp, nullableClass.dateProp) && + Objects.equals(this.datetimeProp, nullableClass.datetimeProp) && + Objects.equals(this.arrayNullableProp, nullableClass.arrayNullableProp) && + Objects.equals(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && + Objects.equals(this.arrayItemsNullable, nullableClass.arrayItemsNullable) && + Objects.equals(this.objectNullableProp, nullableClass.objectNullableProp) && + Objects.equals(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && + Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable) && + super.equals(o); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(integerProp, numberProp, booleanProp, stringProp, dateProp, datetimeProp, arrayNullableProp, arrayAndItemsNullableProp, arrayItemsNullable, objectNullableProp, objectAndItemsNullableProp, objectItemsNullable, super.hashCode()); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NullableClass {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" integerProp: ").append(toIndentedString(integerProp)).append("\n"); + sb.append(" numberProp: ").append(toIndentedString(numberProp)).append("\n"); + sb.append(" booleanProp: ").append(toIndentedString(booleanProp)).append("\n"); + sb.append(" stringProp: ").append(toIndentedString(stringProp)).append("\n"); + sb.append(" dateProp: ").append(toIndentedString(dateProp)).append("\n"); + sb.append(" datetimeProp: ").append(toIndentedString(datetimeProp)).append("\n"); + sb.append(" arrayNullableProp: ").append(toIndentedString(arrayNullableProp)).append("\n"); + sb.append(" arrayAndItemsNullableProp: ").append(toIndentedString(arrayAndItemsNullableProp)).append("\n"); + sb.append(" arrayItemsNullable: ").append(toIndentedString(arrayItemsNullable)).append("\n"); + sb.append(" objectNullableProp: ").append(toIndentedString(objectNullableProp)).append("\n"); + sb.append(" objectAndItemsNullableProp: ").append(toIndentedString(objectAndItemsNullableProp)).append("\n"); + sb.append(" objectItemsNullable: ").append(toIndentedString(objectItemsNullable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("integer_prop"); + openapiFields.add("number_prop"); + openapiFields.add("boolean_prop"); + openapiFields.add("string_prop"); + openapiFields.add("date_prop"); + openapiFields.add("datetime_prop"); + openapiFields.add("array_nullable_prop"); + openapiFields.add("array_and_items_nullable_prop"); + openapiFields.add("array_items_nullable"); + openapiFields.add("object_nullable_prop"); + openapiFields.add("object_and_items_nullable_prop"); + openapiFields.add("object_items_nullable"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NullableClass.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NullableClass' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NullableClass.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NullableClass value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public NullableClass read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!NullableClass.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `NullableClass` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NullableShape.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NullableShape.java new file mode 100644 index 00000000000..67b42a30572 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NullableShape.java @@ -0,0 +1,225 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Quadrilateral; +import org.openapitools.client.model.Triangle; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class NullableShape extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(NullableShape.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NullableShape.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NullableShape' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class)); + final TypeAdapter adapterTriangle = gson.getDelegateAdapter(this, TypeToken.get(Triangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NullableShape value) throws IOException { + // check if the actual instance is of the type `Quadrilateral` + if (value.getActualInstance() instanceof Quadrilateral) { + JsonObject obj = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `Triangle` + if (value.getActualInstance() instanceof Triangle) { + JsonObject obj = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle"); + } + + @Override + public NullableShape read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + + // deserialize Quadrilateral + try { + deserialized = adapterQuadrilateral.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Quadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e); + } + + // deserialize Triangle + try { + deserialized = adapterTriangle.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Triangle'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Triangle'", e); + } + + if (match == 1) { + NullableShape ret = new NullableShape(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for NullableShape: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public NullableShape() { + super("oneOf", Boolean.TRUE); + } + + public NullableShape(Quadrilateral o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + public NullableShape(Triangle o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + static { + schemas.put("Quadrilateral", new GenericType() { + }); + schemas.put("Triangle", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return NullableShape.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Quadrilateral, Triangle + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance == null) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Quadrilateral) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Triangle) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Quadrilateral, Triangle"); + } + + /** + * Get the actual instance, which can be the following: + * Quadrilateral, Triangle + * + * @return The actual instance (Quadrilateral, Triangle) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Quadrilateral` + * @throws ClassCastException if the instance is not `Quadrilateral` + */ + public Quadrilateral getQuadrilateral() throws ClassCastException { + return (Quadrilateral)super.getActualInstance(); + } + + /** + * Get the actual instance of `Triangle`. If the actual instance is not `Triangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Triangle` + * @throws ClassCastException if the instance is not `Triangle` + */ + public Triangle getTriangle() throws ClassCastException { + return (Triangle)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NumberOnly.java new file mode 100644 index 00000000000..7dc78d63d07 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -0,0 +1,163 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * NumberOnly + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class NumberOnly { + public static final String SERIALIZED_NAME_JUST_NUMBER = "JustNumber"; + @SerializedName(SERIALIZED_NAME_JUST_NUMBER) + private BigDecimal justNumber; + + public NumberOnly() { + } + + public NumberOnly justNumber(BigDecimal justNumber) { + + this.justNumber = justNumber; + return this; + } + + /** + * Get justNumber + * @return justNumber + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public BigDecimal getJustNumber() { + return justNumber; + } + + + public void setJustNumber(BigDecimal justNumber) { + this.justNumber = justNumber; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(this.justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberOnly {\n"); + sb.append(" justNumber: ").append(toIndentedString(justNumber)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("JustNumber"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!NumberOnly.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'NumberOnly' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(NumberOnly.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, NumberOnly value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public NumberOnly read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!NumberOnly.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `NumberOnly` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java new file mode 100644 index 00000000000..654a4415afb --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -0,0 +1,270 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.DeprecatedObject; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ObjectWithDeprecatedFields + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ObjectWithDeprecatedFields { + public static final String SERIALIZED_NAME_UUID = "uuid"; + @SerializedName(SERIALIZED_NAME_UUID) + private String uuid; + + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + private BigDecimal id; + + public static final String SERIALIZED_NAME_DEPRECATED_REF = "deprecatedRef"; + @SerializedName(SERIALIZED_NAME_DEPRECATED_REF) + private DeprecatedObject deprecatedRef; + + public static final String SERIALIZED_NAME_BARS = "bars"; + @SerializedName(SERIALIZED_NAME_BARS) + private List bars = null; + + public ObjectWithDeprecatedFields() { + } + + public ObjectWithDeprecatedFields uuid(String uuid) { + + this.uuid = uuid; + return this; + } + + /** + * Get uuid + * @return uuid + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getUuid() { + return uuid; + } + + + public void setUuid(String uuid) { + this.uuid = uuid; + } + + + public ObjectWithDeprecatedFields id(BigDecimal id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + * @deprecated + **/ + @Deprecated + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public BigDecimal getId() { + return id; + } + + + public void setId(BigDecimal id) { + this.id = id; + } + + + public ObjectWithDeprecatedFields deprecatedRef(DeprecatedObject deprecatedRef) { + + this.deprecatedRef = deprecatedRef; + return this; + } + + /** + * Get deprecatedRef + * @return deprecatedRef + * @deprecated + **/ + @Deprecated + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public DeprecatedObject getDeprecatedRef() { + return deprecatedRef; + } + + + public void setDeprecatedRef(DeprecatedObject deprecatedRef) { + this.deprecatedRef = deprecatedRef; + } + + + public ObjectWithDeprecatedFields bars(List bars) { + + this.bars = bars; + return this; + } + + public ObjectWithDeprecatedFields addBarsItem(String barsItem) { + if (this.bars == null) { + this.bars = new ArrayList(); + } + this.bars.add(barsItem); + return this; + } + + /** + * Get bars + * @return bars + * @deprecated + **/ + @Deprecated + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getBars() { + return bars; + } + + + public void setBars(List bars) { + this.bars = bars; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ObjectWithDeprecatedFields objectWithDeprecatedFields = (ObjectWithDeprecatedFields) o; + return Objects.equals(this.uuid, objectWithDeprecatedFields.uuid) && + Objects.equals(this.id, objectWithDeprecatedFields.id) && + Objects.equals(this.deprecatedRef, objectWithDeprecatedFields.deprecatedRef) && + Objects.equals(this.bars, objectWithDeprecatedFields.bars); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, id, deprecatedRef, bars); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ObjectWithDeprecatedFields {\n"); + sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" deprecatedRef: ").append(toIndentedString(deprecatedRef)).append("\n"); + sb.append(" bars: ").append(toIndentedString(bars)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("uuid"); + openapiFields.add("id"); + openapiFields.add("deprecatedRef"); + openapiFields.add("bars"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ObjectWithDeprecatedFields.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ObjectWithDeprecatedFields' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ObjectWithDeprecatedFields.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ObjectWithDeprecatedFields value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ObjectWithDeprecatedFields read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ObjectWithDeprecatedFields.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ObjectWithDeprecatedFields` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Order.java new file mode 100644 index 00000000000..531e45320f0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Order.java @@ -0,0 +1,362 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.threeten.bp.OffsetDateTime; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Order + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Order { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + private Long id; + + public static final String SERIALIZED_NAME_PET_ID = "petId"; + @SerializedName(SERIALIZED_NAME_PET_ID) + private Long petId; + + public static final String SERIALIZED_NAME_QUANTITY = "quantity"; + @SerializedName(SERIALIZED_NAME_QUANTITY) + private Integer quantity; + + public static final String SERIALIZED_NAME_SHIP_DATE = "shipDate"; + @SerializedName(SERIALIZED_NAME_SHIP_DATE) + private OffsetDateTime shipDate; + + /** + * Order Status + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + private StatusEnum status; + + public static final String SERIALIZED_NAME_COMPLETE = "complete"; + @SerializedName(SERIALIZED_NAME_COMPLETE) + private Boolean complete = false; + + public Order() { + } + + public Order id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Order petId(Long petId) { + + this.petId = petId; + return this; + } + + /** + * Get petId + * @return petId + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Long getPetId() { + return petId; + } + + + public void setPetId(Long petId) { + this.petId = petId; + } + + + public Order quantity(Integer quantity) { + + this.quantity = quantity; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Integer getQuantity() { + return quantity; + } + + + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + + public Order shipDate(OffsetDateTime shipDate) { + + this.shipDate = shipDate; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + @javax.annotation.Nullable + @ApiModelProperty(example = "2020-02-02T20:20:20.000222Z", value = "") + + public OffsetDateTime getShipDate() { + return shipDate; + } + + + public void setShipDate(OffsetDateTime shipDate) { + this.shipDate = shipDate; + } + + + public Order status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * Order Status + * @return status + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "Order Status") + + public StatusEnum getStatus() { + return status; + } + + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + public Order complete(Boolean complete) { + + this.complete = complete; + return this; + } + + /** + * Get complete + * @return complete + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Boolean getComplete() { + return complete; + } + + + public void setComplete(Boolean complete) { + this.complete = complete; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("id"); + openapiFields.add("petId"); + openapiFields.add("quantity"); + openapiFields.add("shipDate"); + openapiFields.add("status"); + openapiFields.add("complete"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Order.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Order' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Order.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Order value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Order read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Order.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Order` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterComposite.java new file mode 100644 index 00000000000..c0f8c964ff9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -0,0 +1,223 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * OuterComposite + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class OuterComposite { + public static final String SERIALIZED_NAME_MY_NUMBER = "my_number"; + @SerializedName(SERIALIZED_NAME_MY_NUMBER) + private BigDecimal myNumber; + + public static final String SERIALIZED_NAME_MY_STRING = "my_string"; + @SerializedName(SERIALIZED_NAME_MY_STRING) + private String myString; + + public static final String SERIALIZED_NAME_MY_BOOLEAN = "my_boolean"; + @SerializedName(SERIALIZED_NAME_MY_BOOLEAN) + private Boolean myBoolean; + + public OuterComposite() { + } + + public OuterComposite myNumber(BigDecimal myNumber) { + + this.myNumber = myNumber; + return this; + } + + /** + * Get myNumber + * @return myNumber + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public BigDecimal getMyNumber() { + return myNumber; + } + + + public void setMyNumber(BigDecimal myNumber) { + this.myNumber = myNumber; + } + + + public OuterComposite myString(String myString) { + + this.myString = myString; + return this; + } + + /** + * Get myString + * @return myString + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getMyString() { + return myString; + } + + + public void setMyString(String myString) { + this.myString = myString; + } + + + public OuterComposite myBoolean(Boolean myBoolean) { + + this.myBoolean = myBoolean; + return this; + } + + /** + * Get myBoolean + * @return myBoolean + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Boolean getMyBoolean() { + return myBoolean; + } + + + public void setMyBoolean(Boolean myBoolean) { + this.myBoolean = myBoolean; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OuterComposite outerComposite = (OuterComposite) o; + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean); + } + + @Override + public int hashCode() { + return Objects.hash(myNumber, myString, myBoolean); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class OuterComposite {\n"); + sb.append(" myNumber: ").append(toIndentedString(myNumber)).append("\n"); + sb.append(" myString: ").append(toIndentedString(myString)).append("\n"); + sb.append(" myBoolean: ").append(toIndentedString(myBoolean)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("my_number"); + openapiFields.add("my_string"); + openapiFields.add("my_boolean"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!OuterComposite.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'OuterComposite' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(OuterComposite.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, OuterComposite value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public OuterComposite read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!OuterComposite.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `OuterComposite` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnum.java new file mode 100644 index 00000000000..c4e27915c8a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnum.java @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Gets or Sets OuterEnum + */ +@JsonAdapter(OuterEnum.Adapter.class) +public enum OuterEnum { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static OuterEnum fromValue(String value) { + for (OuterEnum b : OuterEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + return null; + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final OuterEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public OuterEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return OuterEnum.fromValue(value); + } + } +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java new file mode 100644 index 00000000000..3345a76b104 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Gets or Sets OuterEnumDefaultValue + */ +@JsonAdapter(OuterEnumDefaultValue.Adapter.class) +public enum OuterEnumDefaultValue { + + PLACED("placed"), + + APPROVED("approved"), + + DELIVERED("delivered"); + + private String value; + + OuterEnumDefaultValue(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static OuterEnumDefaultValue fromValue(String value) { + for (OuterEnumDefaultValue b : OuterEnumDefaultValue.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final OuterEnumDefaultValue enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public OuterEnumDefaultValue read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return OuterEnumDefaultValue.fromValue(value); + } + } +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumInteger.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumInteger.java new file mode 100644 index 00000000000..a62c0647099 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumInteger.java @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Gets or Sets OuterEnumInteger + */ +@JsonAdapter(OuterEnumInteger.Adapter.class) +public enum OuterEnumInteger { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumInteger(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static OuterEnumInteger fromValue(Integer value) { + for (OuterEnumInteger b : OuterEnumInteger.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final OuterEnumInteger enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public OuterEnumInteger read(final JsonReader jsonReader) throws IOException { + Integer value = jsonReader.nextInt(); + return OuterEnumInteger.fromValue(value); + } + } +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java new file mode 100644 index 00000000000..862cb38bbfb --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.annotations.SerializedName; + +import java.io.IOException; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * Gets or Sets OuterEnumIntegerDefaultValue + */ +@JsonAdapter(OuterEnumIntegerDefaultValue.Adapter.class) +public enum OuterEnumIntegerDefaultValue { + + NUMBER_0(0), + + NUMBER_1(1), + + NUMBER_2(2); + + private Integer value; + + OuterEnumIntegerDefaultValue(Integer value) { + this.value = value; + } + + public Integer getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static OuterEnumIntegerDefaultValue fromValue(Integer value) { + for (OuterEnumIntegerDefaultValue b : OuterEnumIntegerDefaultValue.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final OuterEnumIntegerDefaultValue enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public OuterEnumIntegerDefaultValue read(final JsonReader jsonReader) throws IOException { + Integer value = jsonReader.nextInt(); + return OuterEnumIntegerDefaultValue.fromValue(value); + } + } +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ParentPet.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ParentPet.java new file mode 100644 index 00000000000..f96071be437 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ParentPet.java @@ -0,0 +1,144 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.GrandparentAnimal; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ParentPet + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ParentPet extends GrandparentAnimal { + public ParentPet() { + this.petType = this.getClass().getSimpleName(); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + return super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ParentPet {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("pet_type"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("pet_type"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ParentPet.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ParentPet' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ParentPet.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ParentPet value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ParentPet read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ParentPet.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ParentPet` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : ParentPet.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Pet.java new file mode 100644 index 00000000000..5d0065de40d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Pet.java @@ -0,0 +1,387 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Pet + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Pet { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + private Long id; + + public static final String SERIALIZED_NAME_CATEGORY = "category"; + @SerializedName(SERIALIZED_NAME_CATEGORY) + private Category category; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + private String name; + + public static final String SERIALIZED_NAME_PHOTO_URLS = "photoUrls"; + @SerializedName(SERIALIZED_NAME_PHOTO_URLS) + private List photoUrls = new ArrayList(); + + public static final String SERIALIZED_NAME_TAGS = "tags"; + @SerializedName(SERIALIZED_NAME_TAGS) + private List tags = null; + + /** + * pet status in the store + */ + @JsonAdapter(StatusEnum.Adapter.class) + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final StatusEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public StatusEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return StatusEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_STATUS = "status"; + @SerializedName(SERIALIZED_NAME_STATUS) + private StatusEnum status; + + public Pet() { + } + + public Pet id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Pet category(Category category) { + + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Category getCategory() { + return category; + } + + + public void setCategory(Category category) { + this.category = category; + } + + + public Pet name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nonnull + @ApiModelProperty(example = "doggie", required = true, value = "") + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + public Pet photoUrls(List photoUrls) { + + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public List getPhotoUrls() { + return photoUrls; + } + + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + public Pet tags(List tags) { + + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public List getTags() { + return tags; + } + + + public void setTags(List tags) { + this.tags = tags; + } + + + public Pet status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "pet status in the store") + + public StatusEnum getStatus() { + return status; + } + + + public void setStatus(StatusEnum status) { + this.status = status; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("id"); + openapiFields.add("category"); + openapiFields.add("name"); + openapiFields.add("photoUrls"); + openapiFields.add("tags"); + openapiFields.add("status"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("name"); + openapiRequiredFields.add("photoUrls"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Pet.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Pet' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Pet.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Pet value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Pet read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Pet.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Pet` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Pet.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Pig.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Pig.java new file mode 100644 index 00000000000..ea0b58cbf90 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Pig.java @@ -0,0 +1,220 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.BasquePig; +import org.openapitools.client.model.DanishPig; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Pig extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Pig.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Pig.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Pig' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterBasquePig = gson.getDelegateAdapter(this, TypeToken.get(BasquePig.class)); + final TypeAdapter adapterDanishPig = gson.getDelegateAdapter(this, TypeToken.get(DanishPig.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Pig value) throws IOException { + // check if the actual instance is of the type `BasquePig` + if (value.getActualInstance() instanceof BasquePig) { + JsonObject obj = adapterBasquePig.toJsonTree((BasquePig)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `DanishPig` + if (value.getActualInstance() instanceof DanishPig) { + JsonObject obj = adapterDanishPig.toJsonTree((DanishPig)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: BasquePig, DanishPig"); + } + + @Override + public Pig read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + + // deserialize BasquePig + try { + deserialized = adapterBasquePig.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'BasquePig'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'BasquePig'", e); + } + + // deserialize DanishPig + try { + deserialized = adapterDanishPig.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'DanishPig'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'DanishPig'", e); + } + + if (match == 1) { + Pig ret = new Pig(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Pig: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public Pig() { + super("oneOf", Boolean.FALSE); + } + + public Pig(BasquePig o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Pig(DanishPig o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("BasquePig", new GenericType() { + }); + schemas.put("DanishPig", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return Pig.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * BasquePig, DanishPig + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof BasquePig) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof DanishPig) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be BasquePig, DanishPig"); + } + + /** + * Get the actual instance, which can be the following: + * BasquePig, DanishPig + * + * @return The actual instance (BasquePig, DanishPig) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `BasquePig`. If the actual instance is not `BasquePig`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `BasquePig` + * @throws ClassCastException if the instance is not `BasquePig` + */ + public BasquePig getBasquePig() throws ClassCastException { + return (BasquePig)super.getActualInstance(); + } + + /** + * Get the actual instance of `DanishPig`. If the actual instance is not `DanishPig`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `DanishPig` + * @throws ClassCastException if the instance is not `DanishPig` + */ + public DanishPig getDanishPig() throws ClassCastException { + return (DanishPig)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Quadrilateral.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Quadrilateral.java new file mode 100644 index 00000000000..b91dda2eece --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Quadrilateral.java @@ -0,0 +1,220 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ComplexQuadrilateral; +import org.openapitools.client.model.SimpleQuadrilateral; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Quadrilateral extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Quadrilateral.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Quadrilateral.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Quadrilateral' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterComplexQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(ComplexQuadrilateral.class)); + final TypeAdapter adapterSimpleQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(SimpleQuadrilateral.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Quadrilateral value) throws IOException { + // check if the actual instance is of the type `ComplexQuadrilateral` + if (value.getActualInstance() instanceof ComplexQuadrilateral) { + JsonObject obj = adapterComplexQuadrilateral.toJsonTree((ComplexQuadrilateral)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `SimpleQuadrilateral` + if (value.getActualInstance() instanceof SimpleQuadrilateral) { + JsonObject obj = adapterSimpleQuadrilateral.toJsonTree((SimpleQuadrilateral)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: ComplexQuadrilateral, SimpleQuadrilateral"); + } + + @Override + public Quadrilateral read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + + // deserialize ComplexQuadrilateral + try { + deserialized = adapterComplexQuadrilateral.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'ComplexQuadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'ComplexQuadrilateral'", e); + } + + // deserialize SimpleQuadrilateral + try { + deserialized = adapterSimpleQuadrilateral.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'SimpleQuadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'SimpleQuadrilateral'", e); + } + + if (match == 1) { + Quadrilateral ret = new Quadrilateral(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Quadrilateral: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public Quadrilateral() { + super("oneOf", Boolean.FALSE); + } + + public Quadrilateral(ComplexQuadrilateral o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Quadrilateral(SimpleQuadrilateral o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("ComplexQuadrilateral", new GenericType() { + }); + schemas.put("SimpleQuadrilateral", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return Quadrilateral.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * ComplexQuadrilateral, SimpleQuadrilateral + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof ComplexQuadrilateral) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof SimpleQuadrilateral) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be ComplexQuadrilateral, SimpleQuadrilateral"); + } + + /** + * Get the actual instance, which can be the following: + * ComplexQuadrilateral, SimpleQuadrilateral + * + * @return The actual instance (ComplexQuadrilateral, SimpleQuadrilateral) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `ComplexQuadrilateral`. If the actual instance is not `ComplexQuadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `ComplexQuadrilateral` + * @throws ClassCastException if the instance is not `ComplexQuadrilateral` + */ + public ComplexQuadrilateral getComplexQuadrilateral() throws ClassCastException { + return (ComplexQuadrilateral)super.getActualInstance(); + } + + /** + * Get the actual instance of `SimpleQuadrilateral`. If the actual instance is not `SimpleQuadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `SimpleQuadrilateral` + * @throws ClassCastException if the instance is not `SimpleQuadrilateral` + */ + public SimpleQuadrilateral getSimpleQuadrilateral() throws ClassCastException { + return (SimpleQuadrilateral)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java new file mode 100644 index 00000000000..e6fc7e3d348 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java @@ -0,0 +1,170 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * QuadrilateralInterface + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class QuadrilateralInterface { + public static final String SERIALIZED_NAME_QUADRILATERAL_TYPE = "quadrilateralType"; + @SerializedName(SERIALIZED_NAME_QUADRILATERAL_TYPE) + private String quadrilateralType; + + public QuadrilateralInterface() { + } + + public QuadrilateralInterface quadrilateralType(String quadrilateralType) { + + this.quadrilateralType = quadrilateralType; + return this; + } + + /** + * Get quadrilateralType + * @return quadrilateralType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getQuadrilateralType() { + return quadrilateralType; + } + + + public void setQuadrilateralType(String quadrilateralType) { + this.quadrilateralType = quadrilateralType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + QuadrilateralInterface quadrilateralInterface = (QuadrilateralInterface) o; + return Objects.equals(this.quadrilateralType, quadrilateralInterface.quadrilateralType); + } + + @Override + public int hashCode() { + return Objects.hash(quadrilateralType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class QuadrilateralInterface {\n"); + sb.append(" quadrilateralType: ").append(toIndentedString(quadrilateralType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("quadrilateralType"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("quadrilateralType"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!QuadrilateralInterface.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'QuadrilateralInterface' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(QuadrilateralInterface.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, QuadrilateralInterface value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public QuadrilateralInterface read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!QuadrilateralInterface.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `QuadrilateralInterface` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : QuadrilateralInterface.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java new file mode 100644 index 00000000000..d842df280fa --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -0,0 +1,191 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ReadOnlyFirst + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ReadOnlyFirst { + public static final String SERIALIZED_NAME_BAR = "bar"; + @SerializedName(SERIALIZED_NAME_BAR) + private String bar; + + public static final String SERIALIZED_NAME_BAZ = "baz"; + @SerializedName(SERIALIZED_NAME_BAZ) + private String baz; + + public ReadOnlyFirst() { + } + + + public ReadOnlyFirst( + String bar + ) { + this(); + this.bar = bar; + } + + /** + * Get bar + * @return bar + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getBar() { + return bar; + } + + + + + public ReadOnlyFirst baz(String baz) { + + this.baz = baz; + return this; + } + + /** + * Get baz + * @return baz + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getBaz() { + return baz; + } + + + public void setBaz(String baz) { + this.baz = baz; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ReadOnlyFirst {\n"); + sb.append(" bar: ").append(toIndentedString(bar)).append("\n"); + sb.append(" baz: ").append(toIndentedString(baz)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("bar"); + openapiFields.add("baz"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ReadOnlyFirst.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ReadOnlyFirst' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ReadOnlyFirst.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ReadOnlyFirst value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ReadOnlyFirst read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ReadOnlyFirst.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ReadOnlyFirst` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ScaleneTriangle.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ScaleneTriangle.java new file mode 100644 index 00000000000..f7dec655276 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ScaleneTriangle.java @@ -0,0 +1,203 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ShapeInterface; +import org.openapitools.client.model.TriangleInterface; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ScaleneTriangle + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ScaleneTriangle { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + private String shapeType; + + public static final String SERIALIZED_NAME_TRIANGLE_TYPE = "triangleType"; + @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) + private String triangleType; + + public ScaleneTriangle() { + } + + public ScaleneTriangle shapeType(String shapeType) { + + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getShapeType() { + return shapeType; + } + + + public void setShapeType(String shapeType) { + this.shapeType = shapeType; + } + + + public ScaleneTriangle triangleType(String triangleType) { + + this.triangleType = triangleType; + return this; + } + + /** + * Get triangleType + * @return triangleType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getTriangleType() { + return triangleType; + } + + + public void setTriangleType(String triangleType) { + this.triangleType = triangleType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ScaleneTriangle scaleneTriangle = (ScaleneTriangle) o; + return Objects.equals(this.shapeType, scaleneTriangle.shapeType) && + Objects.equals(this.triangleType, scaleneTriangle.triangleType); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, triangleType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ScaleneTriangle {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("shapeType"); + openapiFields.add("triangleType"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("shapeType"); + openapiRequiredFields.add("triangleType"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ScaleneTriangle.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ScaleneTriangle' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ScaleneTriangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ScaleneTriangle value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ScaleneTriangle read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ScaleneTriangle.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ScaleneTriangle` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : ScaleneTriangle.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Shape.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Shape.java new file mode 100644 index 00000000000..df7274029b2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Shape.java @@ -0,0 +1,220 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Quadrilateral; +import org.openapitools.client.model.Triangle; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Shape extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Shape.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Shape.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Shape' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class)); + final TypeAdapter adapterTriangle = gson.getDelegateAdapter(this, TypeToken.get(Triangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Shape value) throws IOException { + // check if the actual instance is of the type `Quadrilateral` + if (value.getActualInstance() instanceof Quadrilateral) { + JsonObject obj = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `Triangle` + if (value.getActualInstance() instanceof Triangle) { + JsonObject obj = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle"); + } + + @Override + public Shape read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + + // deserialize Quadrilateral + try { + deserialized = adapterQuadrilateral.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Quadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e); + } + + // deserialize Triangle + try { + deserialized = adapterTriangle.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Triangle'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Triangle'", e); + } + + if (match == 1) { + Shape ret = new Shape(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Shape: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public Shape() { + super("oneOf", Boolean.FALSE); + } + + public Shape(Quadrilateral o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Shape(Triangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Quadrilateral", new GenericType() { + }); + schemas.put("Triangle", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return Shape.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Quadrilateral, Triangle + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof Quadrilateral) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Triangle) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Quadrilateral, Triangle"); + } + + /** + * Get the actual instance, which can be the following: + * Quadrilateral, Triangle + * + * @return The actual instance (Quadrilateral, Triangle) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Quadrilateral` + * @throws ClassCastException if the instance is not `Quadrilateral` + */ + public Quadrilateral getQuadrilateral() throws ClassCastException { + return (Quadrilateral)super.getActualInstance(); + } + + /** + * Get the actual instance of `Triangle`. If the actual instance is not `Triangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Triangle` + * @throws ClassCastException if the instance is not `Triangle` + */ + public Triangle getTriangle() throws ClassCastException { + return (Triangle)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ShapeInterface.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ShapeInterface.java new file mode 100644 index 00000000000..628c2f7af2b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ShapeInterface.java @@ -0,0 +1,170 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * ShapeInterface + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ShapeInterface { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + private String shapeType; + + public ShapeInterface() { + } + + public ShapeInterface shapeType(String shapeType) { + + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getShapeType() { + return shapeType; + } + + + public void setShapeType(String shapeType) { + this.shapeType = shapeType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ShapeInterface shapeInterface = (ShapeInterface) o; + return Objects.equals(this.shapeType, shapeInterface.shapeType); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ShapeInterface {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("shapeType"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("shapeType"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ShapeInterface.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ShapeInterface' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(ShapeInterface.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ShapeInterface value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public ShapeInterface read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!ShapeInterface.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `ShapeInterface` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : ShapeInterface.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ShapeOrNull.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ShapeOrNull.java new file mode 100644 index 00000000000..7c6f090482a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/ShapeOrNull.java @@ -0,0 +1,225 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Quadrilateral; +import org.openapitools.client.model.Triangle; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ShapeOrNull extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(ShapeOrNull.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!ShapeOrNull.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'ShapeOrNull' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterQuadrilateral = gson.getDelegateAdapter(this, TypeToken.get(Quadrilateral.class)); + final TypeAdapter adapterTriangle = gson.getDelegateAdapter(this, TypeToken.get(Triangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, ShapeOrNull value) throws IOException { + // check if the actual instance is of the type `Quadrilateral` + if (value.getActualInstance() instanceof Quadrilateral) { + JsonObject obj = adapterQuadrilateral.toJsonTree((Quadrilateral)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `Triangle` + if (value.getActualInstance() instanceof Triangle) { + JsonObject obj = adapterTriangle.toJsonTree((Triangle)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: Quadrilateral, Triangle"); + } + + @Override + public ShapeOrNull read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + + // deserialize Quadrilateral + try { + deserialized = adapterQuadrilateral.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Quadrilateral'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Quadrilateral'", e); + } + + // deserialize Triangle + try { + deserialized = adapterTriangle.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'Triangle'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'Triangle'", e); + } + + if (match == 1) { + ShapeOrNull ret = new ShapeOrNull(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for ShapeOrNull: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public ShapeOrNull() { + super("oneOf", Boolean.TRUE); + } + + public ShapeOrNull(Quadrilateral o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + public ShapeOrNull(Triangle o) { + super("oneOf", Boolean.TRUE); + setActualInstance(o); + } + + static { + schemas.put("Quadrilateral", new GenericType() { + }); + schemas.put("Triangle", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return ShapeOrNull.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Quadrilateral, Triangle + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance == null) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Quadrilateral) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Triangle) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Quadrilateral, Triangle"); + } + + /** + * Get the actual instance, which can be the following: + * Quadrilateral, Triangle + * + * @return The actual instance (Quadrilateral, Triangle) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Quadrilateral`. If the actual instance is not `Quadrilateral`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Quadrilateral` + * @throws ClassCastException if the instance is not `Quadrilateral` + */ + public Quadrilateral getQuadrilateral() throws ClassCastException { + return (Quadrilateral)super.getActualInstance(); + } + + /** + * Get the actual instance of `Triangle`. If the actual instance is not `Triangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Triangle` + * @throws ClassCastException if the instance is not `Triangle` + */ + public Triangle getTriangle() throws ClassCastException { + return (Triangle)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java new file mode 100644 index 00000000000..064c5f0996c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java @@ -0,0 +1,203 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.QuadrilateralInterface; +import org.openapitools.client.model.ShapeInterface; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * SimpleQuadrilateral + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class SimpleQuadrilateral { + public static final String SERIALIZED_NAME_SHAPE_TYPE = "shapeType"; + @SerializedName(SERIALIZED_NAME_SHAPE_TYPE) + private String shapeType; + + public static final String SERIALIZED_NAME_QUADRILATERAL_TYPE = "quadrilateralType"; + @SerializedName(SERIALIZED_NAME_QUADRILATERAL_TYPE) + private String quadrilateralType; + + public SimpleQuadrilateral() { + } + + public SimpleQuadrilateral shapeType(String shapeType) { + + this.shapeType = shapeType; + return this; + } + + /** + * Get shapeType + * @return shapeType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getShapeType() { + return shapeType; + } + + + public void setShapeType(String shapeType) { + this.shapeType = shapeType; + } + + + public SimpleQuadrilateral quadrilateralType(String quadrilateralType) { + + this.quadrilateralType = quadrilateralType; + return this; + } + + /** + * Get quadrilateralType + * @return quadrilateralType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getQuadrilateralType() { + return quadrilateralType; + } + + + public void setQuadrilateralType(String quadrilateralType) { + this.quadrilateralType = quadrilateralType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SimpleQuadrilateral simpleQuadrilateral = (SimpleQuadrilateral) o; + return Objects.equals(this.shapeType, simpleQuadrilateral.shapeType) && + Objects.equals(this.quadrilateralType, simpleQuadrilateral.quadrilateralType); + } + + @Override + public int hashCode() { + return Objects.hash(shapeType, quadrilateralType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SimpleQuadrilateral {\n"); + sb.append(" shapeType: ").append(toIndentedString(shapeType)).append("\n"); + sb.append(" quadrilateralType: ").append(toIndentedString(quadrilateralType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("shapeType"); + openapiFields.add("quadrilateralType"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("shapeType"); + openapiRequiredFields.add("quadrilateralType"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!SimpleQuadrilateral.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'SimpleQuadrilateral' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(SimpleQuadrilateral.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, SimpleQuadrilateral value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public SimpleQuadrilateral read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!SimpleQuadrilateral.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `SimpleQuadrilateral` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : SimpleQuadrilateral.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/SpecialModelName.java new file mode 100644 index 00000000000..dfdbc850f43 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -0,0 +1,192 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * SpecialModelName + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class SpecialModelName { + public static final String SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME = "$special[property.name]"; + @SerializedName(SERIALIZED_NAME_$_SPECIAL_PROPERTY_NAME) + private Long $specialPropertyName; + + public static final String SERIALIZED_NAME_SPECIAL_MODEL_NAME = "_special_model.name_"; + @SerializedName(SERIALIZED_NAME_SPECIAL_MODEL_NAME) + private String specialModelName; + + public SpecialModelName() { + } + + public SpecialModelName $specialPropertyName(Long $specialPropertyName) { + + this.$specialPropertyName = $specialPropertyName; + return this; + } + + /** + * Get $specialPropertyName + * @return $specialPropertyName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Long get$SpecialPropertyName() { + return $specialPropertyName; + } + + + public void set$SpecialPropertyName(Long $specialPropertyName) { + this.$specialPropertyName = $specialPropertyName; + } + + + public SpecialModelName specialModelName(String specialModelName) { + + this.specialModelName = specialModelName; + return this; + } + + /** + * Get specialModelName + * @return specialModelName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getSpecialModelName() { + return specialModelName; + } + + + public void setSpecialModelName(String specialModelName) { + this.specialModelName = specialModelName; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName specialModelName = (SpecialModelName) o; + return Objects.equals(this.$specialPropertyName, specialModelName.$specialPropertyName) && + Objects.equals(this.specialModelName, specialModelName.specialModelName); + } + + @Override + public int hashCode() { + return Objects.hash($specialPropertyName, specialModelName); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class SpecialModelName {\n"); + sb.append(" $specialPropertyName: ").append(toIndentedString($specialPropertyName)).append("\n"); + sb.append(" specialModelName: ").append(toIndentedString(specialModelName)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("$special[property.name]"); + openapiFields.add("_special_model.name_"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!SpecialModelName.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'SpecialModelName' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(SpecialModelName.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, SpecialModelName value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public SpecialModelName read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!SpecialModelName.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `SpecialModelName` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Tag.java new file mode 100644 index 00000000000..78ea45ac861 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Tag.java @@ -0,0 +1,192 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Tag + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Tag { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + private String name; + + public Tag() { + } + + public Tag id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public Tag name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getName() { + return name; + } + + + public void setName(String name) { + this.name = name; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("id"); + openapiFields.add("name"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Tag.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Tag' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Tag.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Tag value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Tag read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Tag.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Tag` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Triangle.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Triangle.java new file mode 100644 index 00000000000..e9e70e6be71 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Triangle.java @@ -0,0 +1,261 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.EquilateralTriangle; +import org.openapitools.client.model.IsoscelesTriangle; +import org.openapitools.client.model.ScaleneTriangle; + +import javax.ws.rs.core.GenericType; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Triangle extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(Triangle.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Triangle.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Triangle' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterEquilateralTriangle = gson.getDelegateAdapter(this, TypeToken.get(EquilateralTriangle.class)); + final TypeAdapter adapterIsoscelesTriangle = gson.getDelegateAdapter(this, TypeToken.get(IsoscelesTriangle.class)); + final TypeAdapter adapterScaleneTriangle = gson.getDelegateAdapter(this, TypeToken.get(ScaleneTriangle.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Triangle value) throws IOException { + // check if the actual instance is of the type `EquilateralTriangle` + if (value.getActualInstance() instanceof EquilateralTriangle) { + JsonObject obj = adapterEquilateralTriangle.toJsonTree((EquilateralTriangle)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `IsoscelesTriangle` + if (value.getActualInstance() instanceof IsoscelesTriangle) { + JsonObject obj = adapterIsoscelesTriangle.toJsonTree((IsoscelesTriangle)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + // check if the actual instance is of the type `ScaleneTriangle` + if (value.getActualInstance() instanceof ScaleneTriangle) { + JsonObject obj = adapterScaleneTriangle.toJsonTree((ScaleneTriangle)value.getActualInstance()).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + throw new IOException("Failed to deserialize as the type doesn't match oneOf schemas: EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle"); + } + + @Override + public Triangle read(JsonReader in) throws IOException { + Object deserialized = null; + JsonObject jsonObject = elementAdapter.read(in).getAsJsonObject(); + + int match = 0; + + // deserialize EquilateralTriangle + try { + deserialized = adapterEquilateralTriangle.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'EquilateralTriangle'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'EquilateralTriangle'", e); + } + + // deserialize IsoscelesTriangle + try { + deserialized = adapterIsoscelesTriangle.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'IsoscelesTriangle'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'IsoscelesTriangle'", e); + } + + // deserialize ScaleneTriangle + try { + deserialized = adapterScaleneTriangle.fromJsonTree(jsonObject); + match++; + log.log(Level.FINER, "Input data matches schema 'ScaleneTriangle'"); + } catch (Exception e) { + // deserialization failed, continue + log.log(Level.FINER, "Input data does not match schema 'ScaleneTriangle'", e); + } + + if (match == 1) { + Triangle ret = new Triangle(); + ret.setActualInstance(deserialized); + return ret; + } + + throw new IOException(String.format("Failed deserialization for Triangle: %d classes match result, expected 1", match)); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map schemas = new HashMap(); + + public Triangle() { + super("oneOf", Boolean.FALSE); + } + + public Triangle(EquilateralTriangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Triangle(IsoscelesTriangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public Triangle(ScaleneTriangle o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("EquilateralTriangle", new GenericType() { + }); + schemas.put("IsoscelesTriangle", new GenericType() { + }); + schemas.put("ScaleneTriangle", new GenericType() { + }); + } + + @Override + public Map getSchemas() { + return Triangle.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle + * + * It could be an instance of the 'oneOf' schemas. + * The oneOf child schemas may themselves be a composed schema (allOf, anyOf, oneOf). + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof EquilateralTriangle) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof IsoscelesTriangle) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof ScaleneTriangle) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle"); + } + + /** + * Get the actual instance, which can be the following: + * EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle + * + * @return The actual instance (EquilateralTriangle, IsoscelesTriangle, ScaleneTriangle) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `EquilateralTriangle`. If the actual instance is not `EquilateralTriangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `EquilateralTriangle` + * @throws ClassCastException if the instance is not `EquilateralTriangle` + */ + public EquilateralTriangle getEquilateralTriangle() throws ClassCastException { + return (EquilateralTriangle)super.getActualInstance(); + } + + /** + * Get the actual instance of `IsoscelesTriangle`. If the actual instance is not `IsoscelesTriangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `IsoscelesTriangle` + * @throws ClassCastException if the instance is not `IsoscelesTriangle` + */ + public IsoscelesTriangle getIsoscelesTriangle() throws ClassCastException { + return (IsoscelesTriangle)super.getActualInstance(); + } + + /** + * Get the actual instance of `ScaleneTriangle`. If the actual instance is not `ScaleneTriangle`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `ScaleneTriangle` + * @throws ClassCastException if the instance is not `ScaleneTriangle` + */ + public ScaleneTriangle getScaleneTriangle() throws ClassCastException { + return (ScaleneTriangle)super.getActualInstance(); + } + +} + diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/TriangleInterface.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/TriangleInterface.java new file mode 100644 index 00000000000..a03456d2a06 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/TriangleInterface.java @@ -0,0 +1,170 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * TriangleInterface + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class TriangleInterface { + public static final String SERIALIZED_NAME_TRIANGLE_TYPE = "triangleType"; + @SerializedName(SERIALIZED_NAME_TRIANGLE_TYPE) + private String triangleType; + + public TriangleInterface() { + } + + public TriangleInterface triangleType(String triangleType) { + + this.triangleType = triangleType; + return this; + } + + /** + * Get triangleType + * @return triangleType + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getTriangleType() { + return triangleType; + } + + + public void setTriangleType(String triangleType) { + this.triangleType = triangleType; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TriangleInterface triangleInterface = (TriangleInterface) o; + return Objects.equals(this.triangleType, triangleInterface.triangleType); + } + + @Override + public int hashCode() { + return Objects.hash(triangleType); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TriangleInterface {\n"); + sb.append(" triangleType: ").append(toIndentedString(triangleType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("triangleType"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("triangleType"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!TriangleInterface.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'TriangleInterface' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(TriangleInterface.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, TriangleInterface value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public TriangleInterface read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!TriangleInterface.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `TriangleInterface` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : TriangleInterface.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/User.java new file mode 100644 index 00000000000..4f60e1ecd73 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/User.java @@ -0,0 +1,504 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.jackson.nullable.JsonNullable; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * User + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class User { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + private Long id; + + public static final String SERIALIZED_NAME_USERNAME = "username"; + @SerializedName(SERIALIZED_NAME_USERNAME) + private String username; + + public static final String SERIALIZED_NAME_FIRST_NAME = "firstName"; + @SerializedName(SERIALIZED_NAME_FIRST_NAME) + private String firstName; + + public static final String SERIALIZED_NAME_LAST_NAME = "lastName"; + @SerializedName(SERIALIZED_NAME_LAST_NAME) + private String lastName; + + public static final String SERIALIZED_NAME_EMAIL = "email"; + @SerializedName(SERIALIZED_NAME_EMAIL) + private String email; + + public static final String SERIALIZED_NAME_PASSWORD = "password"; + @SerializedName(SERIALIZED_NAME_PASSWORD) + private String password; + + public static final String SERIALIZED_NAME_PHONE = "phone"; + @SerializedName(SERIALIZED_NAME_PHONE) + private String phone; + + public static final String SERIALIZED_NAME_USER_STATUS = "userStatus"; + @SerializedName(SERIALIZED_NAME_USER_STATUS) + private Integer userStatus; + + public static final String SERIALIZED_NAME_OBJECT_WITH_NO_DECLARED_PROPS = "objectWithNoDeclaredProps"; + @SerializedName(SERIALIZED_NAME_OBJECT_WITH_NO_DECLARED_PROPS) + private Object objectWithNoDeclaredProps; + + public static final String SERIALIZED_NAME_OBJECT_WITH_NO_DECLARED_PROPS_NULLABLE = "objectWithNoDeclaredPropsNullable"; + @SerializedName(SERIALIZED_NAME_OBJECT_WITH_NO_DECLARED_PROPS_NULLABLE) + private Object objectWithNoDeclaredPropsNullable; + + public static final String SERIALIZED_NAME_ANY_TYPE_PROP = "anyTypeProp"; + @SerializedName(SERIALIZED_NAME_ANY_TYPE_PROP) + private Object anyTypeProp = null; + + public static final String SERIALIZED_NAME_ANY_TYPE_PROP_NULLABLE = "anyTypePropNullable"; + @SerializedName(SERIALIZED_NAME_ANY_TYPE_PROP_NULLABLE) + private Object anyTypePropNullable = null; + + public User() { + } + + public User id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Long getId() { + return id; + } + + + public void setId(Long id) { + this.id = id; + } + + + public User username(String username) { + + this.username = username; + return this; + } + + /** + * Get username + * @return username + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getUsername() { + return username; + } + + + public void setUsername(String username) { + this.username = username; + } + + + public User firstName(String firstName) { + + this.firstName = firstName; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getFirstName() { + return firstName; + } + + + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + + public User lastName(String lastName) { + + this.lastName = lastName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getLastName() { + return lastName; + } + + + public void setLastName(String lastName) { + this.lastName = lastName; + } + + + public User email(String email) { + + this.email = email; + return this; + } + + /** + * Get email + * @return email + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getEmail() { + return email; + } + + + public void setEmail(String email) { + this.email = email; + } + + + public User password(String password) { + + this.password = password; + return this; + } + + /** + * Get password + * @return password + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getPassword() { + return password; + } + + + public void setPassword(String password) { + this.password = password; + } + + + public User phone(String phone) { + + this.phone = phone; + return this; + } + + /** + * Get phone + * @return phone + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public String getPhone() { + return phone; + } + + + public void setPhone(String phone) { + this.phone = phone; + } + + + public User userStatus(Integer userStatus) { + + this.userStatus = userStatus; + return this; + } + + /** + * User Status + * @return userStatus + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "User Status") + + public Integer getUserStatus() { + return userStatus; + } + + + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + + public User objectWithNoDeclaredProps(Object objectWithNoDeclaredProps) { + + this.objectWithNoDeclaredProps = objectWithNoDeclaredProps; + return this; + } + + /** + * test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + * @return objectWithNoDeclaredProps + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value.") + + public Object getObjectWithNoDeclaredProps() { + return objectWithNoDeclaredProps; + } + + + public void setObjectWithNoDeclaredProps(Object objectWithNoDeclaredProps) { + this.objectWithNoDeclaredProps = objectWithNoDeclaredProps; + } + + + public User objectWithNoDeclaredPropsNullable(Object objectWithNoDeclaredPropsNullable) { + + this.objectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + return this; + } + + /** + * test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + * @return objectWithNoDeclaredPropsNullable + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "test code generation for nullable objects. Value must be a map of strings to values or the 'null' value.") + + public Object getObjectWithNoDeclaredPropsNullable() { + return objectWithNoDeclaredPropsNullable; + } + + + public void setObjectWithNoDeclaredPropsNullable(Object objectWithNoDeclaredPropsNullable) { + this.objectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + } + + + public User anyTypeProp(Object anyTypeProp) { + + this.anyTypeProp = anyTypeProp; + return this; + } + + /** + * test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + * @return anyTypeProp + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389") + + public Object getAnyTypeProp() { + return anyTypeProp; + } + + + public void setAnyTypeProp(Object anyTypeProp) { + this.anyTypeProp = anyTypeProp; + } + + + public User anyTypePropNullable(Object anyTypePropNullable) { + + this.anyTypePropNullable = anyTypePropNullable; + return this; + } + + /** + * test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + * @return anyTypePropNullable + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values.") + + public Object getAnyTypePropNullable() { + return anyTypePropNullable; + } + + + public void setAnyTypePropNullable(Object anyTypePropNullable) { + this.anyTypePropNullable = anyTypePropNullable; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus) && + Objects.equals(this.objectWithNoDeclaredProps, user.objectWithNoDeclaredProps) && + Objects.equals(this.objectWithNoDeclaredPropsNullable, user.objectWithNoDeclaredPropsNullable) && + Objects.equals(this.anyTypeProp, user.anyTypeProp) && + Objects.equals(this.anyTypePropNullable, user.anyTypePropNullable); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus, objectWithNoDeclaredProps, objectWithNoDeclaredPropsNullable, anyTypeProp, anyTypePropNullable); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append(" objectWithNoDeclaredProps: ").append(toIndentedString(objectWithNoDeclaredProps)).append("\n"); + sb.append(" objectWithNoDeclaredPropsNullable: ").append(toIndentedString(objectWithNoDeclaredPropsNullable)).append("\n"); + sb.append(" anyTypeProp: ").append(toIndentedString(anyTypeProp)).append("\n"); + sb.append(" anyTypePropNullable: ").append(toIndentedString(anyTypePropNullable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("id"); + openapiFields.add("username"); + openapiFields.add("firstName"); + openapiFields.add("lastName"); + openapiFields.add("email"); + openapiFields.add("password"); + openapiFields.add("phone"); + openapiFields.add("userStatus"); + openapiFields.add("objectWithNoDeclaredProps"); + openapiFields.add("objectWithNoDeclaredPropsNullable"); + openapiFields.add("anyTypeProp"); + openapiFields.add("anyTypePropNullable"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!User.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'User' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(User.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, User value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public User read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!User.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `User` properties"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Whale.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Whale.java new file mode 100644 index 00000000000..c84faf2790b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Whale.java @@ -0,0 +1,230 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Whale + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Whale { + public static final String SERIALIZED_NAME_HAS_BALEEN = "hasBaleen"; + @SerializedName(SERIALIZED_NAME_HAS_BALEEN) + private Boolean hasBaleen; + + public static final String SERIALIZED_NAME_HAS_TEETH = "hasTeeth"; + @SerializedName(SERIALIZED_NAME_HAS_TEETH) + private Boolean hasTeeth; + + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + private String className; + + public Whale() { + } + + public Whale hasBaleen(Boolean hasBaleen) { + + this.hasBaleen = hasBaleen; + return this; + } + + /** + * Get hasBaleen + * @return hasBaleen + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Boolean getHasBaleen() { + return hasBaleen; + } + + + public void setHasBaleen(Boolean hasBaleen) { + this.hasBaleen = hasBaleen; + } + + + public Whale hasTeeth(Boolean hasTeeth) { + + this.hasTeeth = hasTeeth; + return this; + } + + /** + * Get hasTeeth + * @return hasTeeth + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public Boolean getHasTeeth() { + return hasTeeth; + } + + + public void setHasTeeth(Boolean hasTeeth) { + this.hasTeeth = hasTeeth; + } + + + public Whale className(String className) { + + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getClassName() { + return className; + } + + + public void setClassName(String className) { + this.className = className; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Whale whale = (Whale) o; + return Objects.equals(this.hasBaleen, whale.hasBaleen) && + Objects.equals(this.hasTeeth, whale.hasTeeth) && + Objects.equals(this.className, whale.className); + } + + @Override + public int hashCode() { + return Objects.hash(hasBaleen, hasTeeth, className); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Whale {\n"); + sb.append(" hasBaleen: ").append(toIndentedString(hasBaleen)).append("\n"); + sb.append(" hasTeeth: ").append(toIndentedString(hasTeeth)).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("hasBaleen"); + openapiFields.add("hasTeeth"); + openapiFields.add("className"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("className"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Whale.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Whale' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Whale.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Whale value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Whale read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Whale.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Whale` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Whale.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Zebra.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Zebra.java new file mode 100644 index 00000000000..7821c21cacc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Zebra.java @@ -0,0 +1,253 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; + +import java.lang.reflect.Type; +import java.util.HashSet; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; + +/** + * Zebra + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Zebra extends HashMap { + /** + * Gets or Sets type + */ + @JsonAdapter(TypeEnum.Adapter.class) + public enum TypeEnum { + PLAINS("plains"), + + MOUNTAIN("mountain"), + + GREVYS("grevys"); + + private String value; + + TypeEnum(String value) { + this.value = value; + } + + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static TypeEnum fromValue(String value) { + for (TypeEnum b : TypeEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + + public static class Adapter extends TypeAdapter { + @Override + public void write(final JsonWriter jsonWriter, final TypeEnum enumeration) throws IOException { + jsonWriter.value(enumeration.getValue()); + } + + @Override + public TypeEnum read(final JsonReader jsonReader) throws IOException { + String value = jsonReader.nextString(); + return TypeEnum.fromValue(value); + } + } + } + + public static final String SERIALIZED_NAME_TYPE = "type"; + @SerializedName(SERIALIZED_NAME_TYPE) + private TypeEnum type; + + public static final String SERIALIZED_NAME_CLASS_NAME = "className"; + @SerializedName(SERIALIZED_NAME_CLASS_NAME) + private String className; + + public Zebra() { + } + + public Zebra type(TypeEnum type) { + + this.type = type; + return this; + } + + /** + * Get type + * @return type + **/ + @javax.annotation.Nullable + @ApiModelProperty(value = "") + + public TypeEnum getType() { + return type; + } + + + public void setType(TypeEnum type) { + this.type = type; + } + + + public Zebra className(String className) { + + this.className = className; + return this; + } + + /** + * Get className + * @return className + **/ + @javax.annotation.Nonnull + @ApiModelProperty(required = true, value = "") + + public String getClassName() { + return className; + } + + + public void setClassName(String className) { + this.className = className; + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Zebra zebra = (Zebra) o; + return Objects.equals(this.type, zebra.type) && + Objects.equals(this.className, zebra.className) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(type, className, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Zebra {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" className: ").append(toIndentedString(className)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("type"); + openapiFields.add("className"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("className"); + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!Zebra.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'Zebra' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(Zebra.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, Zebra value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + elementAdapter.write(out, obj); + } + + @Override + public Zebra read(JsonReader in) throws IOException { + JsonObject obj = elementAdapter.read(in).getAsJsonObject(); + Set> entries = obj.entrySet();//will return members of your object + // check to see if the JSON string contains additional fields + for (Entry entry: entries) { + if (!Zebra.openapiFields.contains(entry.getKey())) { + throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Zebra` properties"); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : Zebra.openapiRequiredFields) { + if (obj.get(requiredField) == null) { + throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); + } + } + + return thisAdapter.fromJsonTree(obj); + } + + }.nullSafe(); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 00000000000..9edd0ae7bed --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,345 @@ +package org.openapitools.client; + +import static org.hamcrest.CoreMatchers.*; +import static org.junit.Assert.*; + +import java.util.*; +import okhttp3.OkHttpClient; +import org.junit.*; +import org.openapitools.client.auth.*; + +public class ApiClientTest { + ApiClient apiClient; + JSON json; + + @Before + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + + assertTrue(apiClient.isJsonMime("application/json-patch+json")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[] {"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[] {"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[] {"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[] {}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[] {"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[] {"application/xml", "application/json; charset=UTF8"}; + assertEquals( + "application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[] {"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[] {}; + assertNull(apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + /* + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + */ + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testGetAndSetConnectTimeout() { + // connect timeout defaults to 10 seconds + assertEquals(10000, apiClient.getConnectTimeout()); + assertEquals(10000, apiClient.getHttpClient().connectTimeoutMillis()); + + apiClient.setConnectTimeout(0); + assertEquals(0, apiClient.getConnectTimeout()); + assertEquals(0, apiClient.getHttpClient().connectTimeoutMillis()); + + apiClient.setConnectTimeout(10000); + } + + @Test + public void testGetAndSetReadTimeout() { + // read timeout defaults to 10 seconds + assertEquals(10000, apiClient.getReadTimeout()); + assertEquals(10000, apiClient.getHttpClient().readTimeoutMillis()); + + apiClient.setReadTimeout(0); + assertEquals(0, apiClient.getReadTimeout()); + assertEquals(0, apiClient.getHttpClient().readTimeoutMillis()); + + apiClient.setReadTimeout(10000); + } + + @Test + public void testGetAndSetWriteTimeout() { + // write timeout defaults to 10 seconds + assertEquals(10000, apiClient.getWriteTimeout()); + assertEquals(10000, apiClient.getHttpClient().writeTimeoutMillis()); + + apiClient.setWriteTimeout(0); + assertEquals(0, apiClient.getWriteTimeout()); + assertEquals(0, apiClient.getHttpClient().writeTimeoutMillis()); + + apiClient.setWriteTimeout(10000); + } + + @Test + public void testParameterToPairWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPair(null, new Integer(1)); + List pairs_b = apiClient.parameterToPair("", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPair("param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsEmptyString() throws Exception { + // single empty string + List pairs = apiClient.parameterToPair("param-a", " "); + assertEquals(1, pairs.size()); + } + + @Test + public void testParameterToPairWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPair(name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairWhenValueIsCollection() throws Exception { + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + List pairs = apiClient.parameterToPair("param-a", values); + assertEquals(0, pairs.size()); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List objects = new ArrayList(); + objects.add(new Integer(1)); + + List pairs_a = apiClient.parameterToPairs("csv", null, objects); + List pairs_b = apiClient.parameterToPairs("csv", "", objects); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + for (int i = 0; i < values.size(); i++) { + assertEquals( + apiClient.escapeString(apiClient.parameterToString(values.get(i))), + multiPairs.get(i).getValue()); + } + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + if (!delimiter.equals(",")) { + // commas are not escaped because they are reserved characters in URIs + delimiter = apiClient.escapeString(delimiter); + } + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + for (int i = 0; i < values.size(); i++) { + assertEquals( + apiClient.escapeString(apiClient.parameterToString(values.get(i))), + pairValueSplit[i]); + } + } + } + + @Test + public void testSanitizeFilename() { + assertEquals("sun", apiClient.sanitizeFilename("sun")); + assertEquals("sun.gif", apiClient.sanitizeFilename("sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("../sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("/var/tmp/sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("./sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("..\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("c:\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename(".\\sun.gif")); + } + + @Test + public void testNewHttpClient() { + OkHttpClient oldClient = apiClient.getHttpClient(); + apiClient.setHttpClient(oldClient.newBuilder().build()); + assertThat(apiClient.getHttpClient(), is(not(oldClient))); + } + + /** Tests the invariant that the HttpClient for the ApiClient must never be null */ + @Test(expected = NullPointerException.class) + public void testNullHttpClient() { + apiClient.setHttpClient(null); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/ConfigurationTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/ConfigurationTest.java new file mode 100644 index 00000000000..3d6ab82bd3e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package org.openapitools.client; + +import static org.junit.Assert.*; + +import org.junit.*; + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/JSONTest.java new file mode 100644 index 00000000000..c6b3c2345dd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/JSONTest.java @@ -0,0 +1,348 @@ +package org.openapitools.client; + +import static org.junit.Assert.*; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.reflect.TypeToken; +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; +import okio.ByteString; +import org.junit.*; +import org.openapitools.client.model.Order; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.threeten.bp.ZoneId; +import org.threeten.bp.ZoneOffset; +import org.threeten.bp.format.DateTimeFormatter; + +import org.openapitools.client.model.*; + +public class JSONTest { + private ApiClient apiClient = null; + private JSON json = null; + private Order order = null; + + @Before + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + order = new Order(); + } + + @Test + public void testSqlDateTypeAdapter() { + final String str = "\"2015-11-07\""; + final java.sql.Date date = java.sql.Date.valueOf("2015-11-07"); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, java.sql.Date.class), date); + assertEquals( + json.deserialize( + "\"2015-11-07T03:49:09.356" + getCurrentTimezoneOffset() + "\"", + java.sql.Date.class) + .toString(), + date.toString()); + + // custom date format: without day + DateFormat format = new SimpleDateFormat("yyyy-MM", Locale.ROOT); + apiClient.setSqlDateFormat(format); + String dateStr = "\"2015-11\""; + assertEquals( + dateStr, + json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", java.sql.Date.class))); + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11\"", java.sql.Date.class))); + } + + @Test + public void testDateTypeAdapter() { + Calendar cal = new GregorianCalendar(2015, 10, 7, 3, 49, 9); + cal.setTimeZone(TimeZone.getTimeZone("UTC")); + + assertEquals(json.deserialize("\"2015-11-07T05:49:09+02\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 300); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.3Z\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 356); + Date date = cal.getTime(); + + final String utcDate = "\"2015-11-07T03:49:09.356Z\""; + assertEquals(json.deserialize(utcDate, Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T05:49:09.356+02:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-01:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356Z\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-0100\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356456789Z\"", Date.class), date); + + assertEquals(utcDate, json.serialize(date)); + + // custom datetime format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ROOT); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + + String dateStr = "\"2015-11-07T13:49:09+10:00\""; + assertEquals( + dateStr, + json.serialize(json.deserialize("\"2015-11-07T03:49:09+00:00\"", Date.class))); + assertEquals( + dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", Date.class))); + assertEquals( + dateStr, + json.serialize(json.deserialize("\"2015-11-07T00:49:09-03:00\"", Date.class))); + + try { + // invalid time zone format + json.deserialize("\"2015-11-07T03:49:09+00\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + try { + // unexpected miliseconds + json.deserialize("\"2015-11-07T03:49:09.000Z\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + } + + @Test + public void testOffsetDateTimeTypeAdapter() { + final String str = "\"2016-09-09T08:02:03.123-03:00\""; + OffsetDateTime date = + OffsetDateTime.of(2016, 9, 9, 8, 2, 3, 123000000, ZoneOffset.of("-3")); + + assertEquals(str, json.serialize(date)); + // Use toString() instead of isEqual to verify that the offset is preserved + assertEquals(json.deserialize(str, OffsetDateTime.class).toString(), date.toString()); + } + + @Test + public void testLocalDateTypeAdapter() { + final String str = "\"2016-09-09\""; + final LocalDate date = LocalDate.of(2016, 9, 9); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, LocalDate.class), date); + } + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.serialize(order); + Type type = new TypeToken() {}.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter datetimeFormat = + DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(datetimeFormat.parse(dateStr, OffsetDateTime.FROM)); + + String str = json.serialize(order); + Type type = new TypeToken() {}.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testByteArrayTypeAdapterSerialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + + // Act + String serializedBytesWithQuotes = json.serialize(expectedBytes); + + // Assert + String serializedBytes = + serializedBytesWithQuotes.substring(1, serializedBytesWithQuotes.length() - 1); + if (json.getGson().htmlSafe()) { + serializedBytes = serializedBytes.replaceAll("\\\\u003d", "="); + } + ByteString actualAsByteString = ByteString.decodeBase64(serializedBytes); + byte[] actualBytes = actualAsByteString.toByteArray(); + assertEquals(expectedBytesAsString, new String(actualBytes, StandardCharsets.UTF_8)); + } + + @Test + public void testByteArrayTypeAdapterDeserialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + final ByteString expectedByteString = ByteString.of(expectedBytes); + final String serializedBytes = expectedByteString.base64(); + final String serializedBytesWithQuotes = "\"" + serializedBytes + "\""; + Type type = new TypeToken() {}.getType(); + + // Act + byte[] actualDeserializedBytes = json.deserialize(serializedBytesWithQuotes, type); + + // Assert + assertEquals( + expectedBytesAsString, new String(actualDeserializedBytes, StandardCharsets.UTF_8)); + } + + @Test(expected = IllegalArgumentException.class) + public void testRequiredFieldException() { + // test json string missing required field(s) to ensure exception is thrown + Gson gson = json.getGson(); + //Gson gson = new GsonBuilder() + // .registerTypeAdapter(Pet.class, new Pet.CustomDeserializer()) + // .create(); + String json = "{\"id\": 5847, \"name\":\"tag test 1\"}"; // missing photoUrls (required field) + //String json = "{\"id2\": 5847, \"name\":\"tag test 1\"}"; + //String json = "{\"id\": 5847}"; + Pet p = gson.fromJson(json, Pet.class); + } + + @Test(expected = IllegalArgumentException.class) + public void testAdditionalFieldException() { + // test json string with additional field(s) to ensure exception is thrown + Gson gson = json.getGson(); + //Gson gson = new GsonBuilder() + // .registerTypeAdapter(Tag.class, new Tag.CustomDeserializer()) + // .create(); + String json = "{\"id\": 5847, \"name\":\"tag test 1\", \"new-field\": true}"; + Tag t = gson.fromJson(json, Tag.class); + } + + @Test + public void testCustomDeserializer() { + // test the custom deserializer to ensure it can deserialize json payload into objects + Gson gson = json.getGson(); + //Gson gson = new GsonBuilder() + // .registerTypeAdapter(Tag.class, new Tag.CustomDeserializer()) + // .create(); + // id and name + String json = "{\"id\": 5847, \"name\":\"tag test 1\"}"; + Tag t = gson.fromJson(json, Tag.class); + assertEquals(t.getName(), "tag test 1"); + assertEquals(t.getId(), Long.valueOf(5847L)); + + // name only + String json2 = "{\"name\":\"tag test 1\"}"; + Tag t2 = gson.fromJson(json2, Tag.class); + assertEquals(t2.getName(), "tag test 1"); + assertEquals(t2.getId(), null); + + // with all required fields + String json3 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"]}"; // missing photoUrls (required field) + Pet t3 = gson.fromJson(json3, Pet.class); + assertEquals(t3.getName(), "pet test 1"); + assertEquals(t3.getId(), Long.valueOf(5847)); + } + + /** Model tests for Pet */ + @Test + public void testPet() { + // test Pet + Pet model = new Pet(); + model.setId(1029L); + model.setName("Dog"); + + Pet model2 = new Pet(); + model2.setId(1029L); + model2.setName("Dog"); + + Assert.assertTrue(model.equals(model2)); + } + + // Obtained 22JAN2018 from stackoverflow answer by PuguaSoft + // https://stackoverflow.com/questions/11399491/java-timezone-offset + // Direct link https://stackoverflow.com/a/16680815/3166133 + public static String getCurrentTimezoneOffset() { + + TimeZone tz = TimeZone.getDefault(); + Calendar cal = GregorianCalendar.getInstance(tz, Locale.ROOT); + int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); + + String offset = + String.format( + Locale.ROOT, + "%02d:%02d", + Math.abs(offsetInMillis / 3600000), + Math.abs((offsetInMillis / 60000) % 60)); + offset = (offsetInMillis >= 0 ? "+" : "-") + offset; + + return offset; + } + + /** + * Validate a oneOf schema can be deserialized into the expected class. + * The oneOf schema does not have a discriminator. + */ + @Test + public void testOneOfSchemaWithoutDiscriminator() throws Exception { + // BananaReq and AppleReq have explicitly defined properties that are different by name. + // There is no discriminator property. + { + String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false }"; + + // make sure deserialization works for pojo object + AppleReq a = json.getGson().fromJson(str, AppleReq.class); + assertEquals(a.getCultivar(), "golden delicious"); + assertEquals(a.getMealy(), false); + + FruitReq o = json.getGson().fromJson(str, FruitReq.class); + assertTrue(o.getActualInstance() instanceof AppleReq); + AppleReq inst = (AppleReq) o.getActualInstance(); + assertEquals(inst.getCultivar(), "golden delicious"); + assertEquals(inst.getMealy(), false); + assertEquals(json.getGson().toJson(inst), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + + AppleReq inst2 = o.getAppleReq(); + assertEquals(inst2.getCultivar(), "golden delicious"); + assertEquals(inst2.getMealy(), false); + assertEquals(json.getGson().toJson(inst2), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + } + { + // Same test, but this time with additional (undeclared) properties. + // Since FruitReq has additionalProperties: false, deserialization should fail. + String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false, \"garbage_prop\": \"abc\" }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + FruitReq o = json.getGson().fromJson(str, FruitReq.class); + }); + assertTrue(exception.getMessage().contains("Failed deserialization for FruitReq: 0 classes match result")); + } + { + String str = "{ \"lengthCm\": 17 }"; + + // make sure deserialization works for pojo object + BananaReq b = json.getGson().fromJson(str, BananaReq.class); + assertEquals(b.getLengthCm(), new java.math.BigDecimal(17)); + + FruitReq o = json.getGson().fromJson(str, FruitReq.class); + assertTrue(o.getActualInstance() instanceof BananaReq); + BananaReq inst = (BananaReq) o.getActualInstance(); + assertEquals(inst.getLengthCm(), new java.math.BigDecimal(17)); + } + { + // Try to deserialize empty object. This should fail 'oneOf' because none will match + // AppleReq or BananaReq. + String str = "{ }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + json.getGson().fromJson(str, FruitReq.class); + }); + assertTrue(exception.getMessage().contains("Failed deserialization for FruitReq: 0 classes match result, expected 1")); + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/StringUtilTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/StringUtilTest.java new file mode 100644 index 00000000000..f6b87fbaaa1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package org.openapitools.client; + +import static org.junit.Assert.*; + +import org.junit.*; + +public class StringUtilTest { + @Test + public void testContainsIgnoreCase() { + assertTrue(StringUtil.containsIgnoreCase(new String[] {"abc"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[] {"abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[] {"ABC"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[] {null, "abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[] {null, "abc"}, null)); + + assertFalse(StringUtil.containsIgnoreCase(new String[] {"abc"}, "def")); + assertFalse(StringUtil.containsIgnoreCase(new String[] {}, "ABC")); + assertFalse(StringUtil.containsIgnoreCase(new String[] {}, null)); + } + + @Test + public void testJoin() { + String[] array = {"aa", "bb", "cc"}; + assertEquals("aa,bb,cc", StringUtil.join(array, ",")); + assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); + assertEquals("aabbcc", StringUtil.join(array, "")); + assertEquals("aa bb cc", StringUtil.join(array, " ")); + assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); + + assertEquals("", StringUtil.join(new String[] {}, ",")); + assertEquals("abc", StringUtil.join(new String[] {"abc"}, ",")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java new file mode 100644 index 00000000000..af8a9594410 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 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.junit.Ignore; +import org.junit.Test; +import org.openapitools.client.ApiException; +import org.openapitools.client.model.Client; + +/** API tests for AnotherFakeApi */ +@Ignore +public class AnotherFakeApiTest { + + private final AnotherFakeApi api = new AnotherFakeApi(); + + /** + * To test special tags + * + *

    To test special tags and operation ID starting with number + * + * @throws ApiException if the Api call fails + */ + @Test + public void call123testSpecialTagsTest() throws ApiException { + Client body = null; + Client response = api.call123testSpecialTags(body); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/DefaultApiTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/DefaultApiTest.java new file mode 100644 index 00000000000..5459b4b2c1d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/DefaultApiTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.model.InlineResponseDefault; +import org.junit.Test; +import org.junit.Ignore; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for DefaultApi + */ +@Ignore +public class DefaultApiTest { + + private final DefaultApi api = new DefaultApi(); + + + /** + * + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fooGetTest() throws ApiException { + InlineResponseDefault response = api.fooGet(); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/FakeApiTest.java new file mode 100644 index 00000000000..54eb3e8e090 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/FakeApiTest.java @@ -0,0 +1,302 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import java.math.BigDecimal; +import org.openapitools.client.model.Client; +import java.io.File; +import org.openapitools.client.model.FileSchemaTestClass; +import org.openapitools.client.model.HealthCheckResult; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.openapitools.client.model.OuterComposite; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.User; +import org.junit.Test; +import org.junit.Ignore; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +@Ignore +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + + /** + * Health check endpoint + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeHealthGetTest() throws ApiException { + HealthCheckResult response = api.fakeHealthGet(); + // TODO: test validations + } + + /** + * + * + * Test serialization of outer boolean types + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterBooleanSerializeTest() throws ApiException { + Boolean body = null; + Boolean response = api.fakeOuterBooleanSerialize(body); + // TODO: test validations + } + + /** + * + * + * Test serialization of object with outer number type + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterCompositeSerializeTest() throws ApiException { + OuterComposite outerComposite = null; + OuterComposite response = api.fakeOuterCompositeSerialize(outerComposite); + // TODO: test validations + } + + /** + * + * + * Test serialization of outer number types + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterNumberSerializeTest() throws ApiException { + BigDecimal body = null; + BigDecimal response = api.fakeOuterNumberSerialize(body); + // TODO: test validations + } + + /** + * + * + * Test serialization of outer string types + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void fakeOuterStringSerializeTest() throws ApiException { + String body = null; + String response = api.fakeOuterStringSerialize(body); + // TODO: test validations + } + + /** + * Array of Enums + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getArrayOfEnumsTest() throws ApiException { + List response = api.getArrayOfEnums(); + // TODO: test validations + } + + /** + * + * + * For this test, the body for this request much reference a schema named `File`. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBodyWithFileSchemaTest() throws ApiException { + FileSchemaTestClass fileSchemaTestClass = null; + api.testBodyWithFileSchema(fileSchemaTestClass); + // TODO: test validations + } + + /** + * + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBodyWithQueryParamsTest() throws ApiException { + String query = null; + User user = null; + api.testBodyWithQueryParams(query, user); + // TODO: test validations + } + + /** + * To test \"client\" model + * + * To test \"client\" model + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testClientModelTest() throws ApiException { + Client client = null; + Client response = api.testClientModel(client); + // TODO: test validations + } + + /** + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEndpointParametersTest() throws ApiException { + BigDecimal number = null; + Double _double = null; + String patternWithoutDelimiter = null; + byte[] _byte = null; + Integer integer = null; + Integer int32 = null; + Long int64 = null; + Float _float = null; + String string = null; + File binary = null; + LocalDate date = null; + OffsetDateTime dateTime = null; + String password = null; + String paramCallback = null; + api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + // TODO: test validations + } + + /** + * To test enum parameters + * + * To test enum parameters + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumParametersTest() throws ApiException { + List enumHeaderStringArray = null; + String enumHeaderString = null; + List enumQueryStringArray = null; + String enumQueryString = null; + Integer enumQueryInteger = null; + Double enumQueryDouble = null; + List enumFormStringArray = null; + String enumFormString = null; + api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + // TODO: test validations + } + + /** + * Fake endpoint to test group parameters (optional) + * + * Fake endpoint to test group parameters (optional) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testGroupParametersTest() throws ApiException { + Integer requiredStringGroup = null; + Boolean requiredBooleanGroup = null; + Long requiredInt64Group = null; + Integer stringGroup = null; + Boolean booleanGroup = null; + Long int64Group = null; + api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group) + .stringGroup(stringGroup) + .booleanGroup(booleanGroup) + .int64Group(int64Group) + .execute(); + // TODO: test validations + } + + /** + * test inline additionalProperties + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testInlineAdditionalPropertiesTest() throws ApiException { + Map requestBody = null; + api.testInlineAdditionalProperties(requestBody); + // TODO: test validations + } + + /** + * test json serialization of form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testJsonFormDataTest() throws ApiException { + String param = null; + String param2 = null; + api.testJsonFormData(param, param2); + // TODO: test validations + } + + /** + * + * + * To test the collection format in query parameters + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryParameterCollectionFormatTest() throws ApiException { + List pipe = null; + List ioutil = null; + List http = null; + List url = null; + List context = null; + api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java new file mode 100644 index 00000000000..16b1c5afa71 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java @@ -0,0 +1,41 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 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.junit.Ignore; +import org.junit.Test; +import org.openapitools.client.ApiException; +import org.openapitools.client.model.Client; + +/** API tests for FakeClassnameTags123Api */ +@Ignore +public class FakeClassnameTags123ApiTest { + + private final FakeClassnameTags123Api api = new FakeClassnameTags123Api(); + + /** + * To test class name in snake case + * + *

    To test class name in snake case + * + * @throws ApiException if the Api call fails + */ + @Test + public void testClassnameTest() throws ApiException { + Client body = null; + Client response = api.testClassname(body); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/PetApiTest.java new file mode 100644 index 00000000000..a4e3dcec14c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/PetApiTest.java @@ -0,0 +1,575 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 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 static org.junit.Assert.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; +import org.junit.*; +import org.openapitools.client.*; +import org.openapitools.client.ApiException; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.model.Pet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** API tests for PetApi */ +public class PetApiTest { + + private PetApi api = new PetApi(); + private final Logger LOG = LoggerFactory.getLogger(PetApiTest.class); + // In the circle.yml file, /etc/host is configured with an entry to resolve petstore.swagger.io + // to 127.0.0.1 + private static String basePath = "http://petstore.swagger.io:80/v2"; + + @Before + public void setup() { + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + api.getApiClient().setBasePath(basePath); + } + + @Test + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals(basePath, api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setVerifyingSsl(true); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals(basePath, api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertPetMatches(pet, fetched); + api.deletePet(pet.getId(), null); + } + + @Test + public void testCreateAndGetPetWithHttpInfo() throws Exception { + Pet pet = createPet(); + api.addPetWithHttpInfo(pet); + + ApiResponse resp = api.getPetByIdWithHttpInfo(pet.getId()); + assertEquals(200, resp.getStatusCode()); + assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0)); + Pet fetched = resp.getData(); + + assertPetMatches(pet, fetched); + api.deletePet(pet.getId(), null); + } + + @Test + public void testCreateAndGetPetAsync() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + // to store returned Pet or error message/exception + final Map result = new HashMap(); + + api.getPetByIdAsync( + pet.getId(), + new ApiCallback() { + @Override + public void onFailure( + ApiException e, + int statusCode, + Map> responseHeaders) { + result.put("error", e.getMessage()); + } + + @Override + public void onSuccess( + Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + + @Override + public void onUploadProgress( + long bytesWritten, long contentLength, boolean done) { + // empty + } + + @Override + public void onDownloadProgress( + long bytesRead, long contentLength, boolean done) { + // empty + } + }); + + // wait for the asynchronous call to finish (at most 10 seconds) + final int maxTry = 10; + int tryCount = 1; + Pet fetched = null; + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("error") != null) fail((String) result.get("error")); + if (result.get("pet") != null) { + fetched = (Pet) result.get("pet"); + break; + } + } while (result.isEmpty()); + assertPetMatches(pet, fetched); + api.deletePet(pet.getId(), null); + } + + @Test + public void testCreateAndGetPetAsyncInvalidID() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + // to store returned Pet or error message/exception + final Map result = new HashMap(); + + // test getting a nonexistent pet + result.clear(); + api.getPetByIdAsync( + -10000L, + new ApiCallback() { + @Override + public void onFailure( + ApiException e, + int statusCode, + Map> responseHeaders) { + result.put("exception", e); + } + + @Override + public void onSuccess( + Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + + @Override + public void onUploadProgress( + long bytesWritten, long contentLength, boolean done) { + // empty + } + + @Override + public void onDownloadProgress( + long bytesRead, long contentLength, boolean done) { + // empty + } + }); + + // wait for the asynchronous call to finish (at most 10 seconds) + final int maxTry = 10; + int tryCount = 1; + Pet fetched = null; + ApiException exception = null; + + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("pet") != null) fail("expected an error"); + if (result.get("exception") != null) { + exception = (ApiException) result.get("exception"); + break; + } + } while (result.isEmpty()); + assertNotNull(exception); + assertEquals(404, exception.getCode()); + assertEquals("Not Found", exception.getMessage()); + assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0)); + api.deletePet(pet.getId(), null); + } + + @Test + public void testCreateAndGetMultiplePetsAsync() throws Exception { + Pet pet1 = createPet(); + Pet pet2 = createPet(); + + final CountDownLatch addLatch = new CountDownLatch(2); + final TestApiCallback addCallback1 = new TestApiCallback(addLatch); + final TestApiCallback addCallback2 = new TestApiCallback(addLatch); + + // Make 2 simultaneous calls + api.addPetAsync(pet1, addCallback1); + api.addPetAsync(pet2, addCallback2); + + // wait for both asynchronous calls to finish (at most 10 seconds) + assertTrue(addLatch.await(10, TimeUnit.SECONDS)); + + assertTrue(addCallback1.isDone()); + assertTrue(addCallback2.isDone()); + + if (!addCallback1.isSuccess()) throw addCallback1.getException(); + if (!addCallback2.isSuccess()) throw addCallback2.getException(); + + assertValidProgress(addCallback1.getUploadProgress()); + assertValidProgress(addCallback2.getUploadProgress()); + + final CountDownLatch getLatch = new CountDownLatch(3); + final TestApiCallback getCallback1 = new TestApiCallback(getLatch); + final TestApiCallback getCallback2 = new TestApiCallback(getLatch); + final TestApiCallback getCallback3 = new TestApiCallback(getLatch); + + api.getPetByIdAsync(pet1.getId(), getCallback1); + api.getPetByIdAsync(pet2.getId(), getCallback2); + // Get nonexistent pet + api.getPetByIdAsync(-10000L, getCallback3); + + // wait for all asynchronous calls to finish (at most 10 seconds) + assertTrue(getLatch.await(10, TimeUnit.SECONDS)); + + assertTrue(getCallback1.isDone()); + assertTrue(getCallback2.isDone()); + assertTrue(getCallback3.isDone()); + + if (!getCallback1.isSuccess()) throw getCallback1.getException(); + if (!getCallback2.isSuccess()) throw getCallback2.getException(); + + assertPetMatches(pet1, getCallback1.getResult()); + assertPetMatches(pet2, getCallback2.getResult()); + + assertValidProgress(getCallback1.getDownloadProgress()); + assertValidProgress(getCallback2.getDownloadProgress()); + + // Last callback should fail with ApiException + assertFalse(getCallback3.isSuccess()); + final ApiException exception = getCallback3.getException(); + assertNotNull(exception); + assertEquals(404, exception.getCode()); + api.deletePet(pet1.getId(), null); + api.deletePet(pet2.getId(), null); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertPetMatches(pet, fetched); + api.deletePet(pet.getId(), null); + } + + @Test + public void testFindPetsByStatus() throws Exception { + assertEquals(basePath, api.getApiClient().getBasePath()); + Pet pet = createPet(); + api.addPet(pet); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.PENDING); + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList("pending")); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + + api.deletePet(pet.getId(), null); + } + + @Test + @Ignore + public void testFindPetsByTags() throws Exception { + Pet pet = createPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + Tag tag1 = new Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags((Arrays.asList("friendly"))); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + + api.deletePet(pet.getId(), null); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + api.deletePet(pet.getId(), null); + } + + @Test + @Ignore + public void testDeletePet() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(pet.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + LOG.info("Code: {}. Message: {}", e.getCode(), e.getMessage()); + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + api.deletePet(pet.getId(), null); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls( + (Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"))); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls( + (Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"))); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createPet() { + Pet pet = new Pet(); + pet.setId(ThreadLocalRandom.current().nextLong(Long.MAX_VALUE)); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = + (Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o, ApiClient apiClient) { + return apiClient.getJSON().serialize(o); + } + + private T deserializeJson(String json, Type type, ApiClient apiClient) { + return (T) apiClient.getJSON().deserialize(json, type); + } + + private void assertPetMatches(Pet expected, Pet actual) { + assertNotNull(actual); + assertEquals(expected.getId(), actual.getId()); + assertNotNull(actual.getCategory()); + assertEquals(expected.getCategory().getName(), actual.getCategory().getName()); + } + + /** + * Assert that the given upload/download progress list satisfies the following constraints: + * + *

    - List is not empty - Byte count should be nondecreasing - The last element, and only the + * last element, should have done=true + */ + private void assertValidProgress(List progressList) { + assertFalse(progressList.isEmpty()); + + Progress prev = null; + int index = 0; + for (Progress progress : progressList) { + if (prev != null) { + if (prev.done || prev.bytes > progress.bytes) { + fail("Progress list out of order at index " + index + ": " + progressList); + } + } + prev = progress; + index += 1; + } + + if (!prev.done) { + fail("Last progress item should have done=true: " + progressList); + } + } + + private static class TestApiCallback implements ApiCallback { + + private final CountDownLatch latch; + private final ConcurrentLinkedQueue uploadProgress = + new ConcurrentLinkedQueue(); + private final ConcurrentLinkedQueue downloadProgress = + new ConcurrentLinkedQueue(); + + private boolean done; + private boolean success; + private ApiException exception; + private T result; + + public TestApiCallback(CountDownLatch latch) { + this.latch = latch; + this.done = false; + } + + @Override + public void onFailure( + ApiException e, int statusCode, Map> responseHeaders) { + exception = e; + this.done = true; + this.success = false; + latch.countDown(); + } + + @Override + public void onSuccess(T result, int statusCode, Map> responseHeaders) { + this.result = result; + this.done = true; + this.success = true; + latch.countDown(); + } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + uploadProgress.add(new Progress(bytesWritten, contentLength, done)); + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + downloadProgress.add(new Progress(bytesRead, contentLength, done)); + } + + public boolean isDone() { + return done; + } + + public boolean isSuccess() { + return success; + } + + public ApiException getException() { + return exception; + } + + public T getResult() { + return result; + } + + public List getUploadProgress() { + return new ArrayList(uploadProgress); + } + + public List getDownloadProgress() { + return new ArrayList(downloadProgress); + } + } + + private static class Progress { + public final long bytes; + public final long contentLength; + public final boolean done; + + public Progress(long bytes, long contentLength, boolean done) { + this.bytes = bytes; + this.contentLength = contentLength; + this.done = done; + } + + @Override + public String toString() { + return ""; + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/StoreApiTest.java new file mode 100644 index 00000000000..41c551458ed --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/StoreApiTest.java @@ -0,0 +1,86 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 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 java.util.Map; +import org.junit.Ignore; +import org.junit.Test; +import org.openapitools.client.ApiException; +import org.openapitools.client.model.Order; + +/** API tests for StoreApi */ +@Ignore +public class StoreApiTest { + + private final StoreApi api = new StoreApi(); + + /** + * Delete purchase order by ID + * + *

    For valid response try integer IDs with value < 1000. Anything above 1000 or + * nonintegers will generate API errors + * + * @throws ApiException if the Api call fails + */ + @Test + public void deleteOrderTest() throws ApiException { + String orderId = null; + api.deleteOrder(orderId); + + // TODO: test validations + } + + /** + * Returns pet inventories by status + * + *

    Returns a map of status codes to quantities + * + * @throws ApiException if the Api call fails + */ + @Test + public void getInventoryTest() throws ApiException { + Map response = api.getInventory(); + + // TODO: test validations + } + + /** + * Find purchase order by ID + * + *

    For valid response try integer IDs with value <= 5 or > 10. Other values will + * generated exceptions + * + * @throws ApiException if the Api call fails + */ + @Test + public void getOrderByIdTest() throws ApiException { + Long orderId = null; + Order response = api.getOrderById(orderId); + + // TODO: test validations + } + + /** + * Place an order for a pet + * + * @throws ApiException if the Api call fails + */ + @Test + public void placeOrderTest() throws ApiException { + Order body = null; + Order response = api.placeOrder(body); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/UserApiTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/UserApiTest.java new file mode 100644 index 00000000000..364b90cab31 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/api/UserApiTest.java @@ -0,0 +1,138 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 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 java.util.List; +import org.junit.Ignore; +import org.junit.Test; +import org.openapitools.client.ApiException; +import org.openapitools.client.model.User; + +/** API tests for UserApi */ +@Ignore +public class UserApiTest { + + private final UserApi api = new UserApi(); + + /** + * Create user + * + *

    This can only be done by the logged in user. + * + * @throws ApiException if the Api call fails + */ + @Test + public void createUserTest() throws ApiException { + User body = null; + api.createUser(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * @throws ApiException if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() throws ApiException { + List body = null; + api.createUsersWithArrayInput(body); + + // TODO: test validations + } + + /** + * Creates list of users with given input array + * + * @throws ApiException if the Api call fails + */ + @Test + public void createUsersWithListInputTest() throws ApiException { + List body = null; + api.createUsersWithListInput(body); + + // TODO: test validations + } + + /** + * Delete user + * + *

    This can only be done by the logged in user. + * + * @throws ApiException if the Api call fails + */ + @Test + public void deleteUserTest() throws ApiException { + String username = null; + api.deleteUser(username); + + // TODO: test validations + } + + /** + * Get user by user name + * + * @throws ApiException if the Api call fails + */ + @Test + public void getUserByNameTest() throws ApiException { + String username = null; + User response = api.getUserByName(username); + + // TODO: test validations + } + + /** + * Logs user into the system + * + * @throws ApiException if the Api call fails + */ + @Test + public void loginUserTest() throws ApiException { + String username = null; + String password = null; + String response = api.loginUser(username, password); + + // TODO: test validations + } + + /** + * Logs out current logged in user session + * + * @throws ApiException if the Api call fails + */ + @Test + public void logoutUserTest() throws ApiException { + api.logoutUser(); + + // TODO: test validations + } + + /** + * Updated user + * + *

    This can only be done by the logged in user. + * + * @throws ApiException if the Api call fails + */ + @Test + public void updateUserTest() throws ApiException { + String username = null; + User body = null; + api.updateUser(username, body); + + // TODO: test validations + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java new file mode 100644 index 00000000000..f7c2ecec9e1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,119 @@ +package org.openapitools.client.auth; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.*; +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header or cookie parameters + assertEquals(0, headerParams.size()); + assertEquals(0, cookieParams.size()); + } + + @Test + public void testApplyToParamsInQueryWithNullValue() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + assertEquals(0, cookieParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to query or cookie parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } + + @Test + public void testApplyToParamsInHeaderWithNullValue() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey(null); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInCookieWithPrefix() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to query or header parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + assertEquals(1, cookieParams.size()); + assertEquals("Token my-api-token", cookieParams.get("X-API-TOKEN")); + } + + @Test + public void testApplyToParamsInCookieWithNullValue() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN"); + auth.setApiKey(null); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(0, headerParams.size()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java new file mode 100644 index 00000000000..a077d394ada --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,65 @@ +package org.openapitools.client.auth; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.*; +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @Before + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to query or cookie parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " + // prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + + // null username and password should be ignored + queryParams = new ArrayList(); + headerParams = new HashMap(); + auth.setUsername(null); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java new file mode 100644 index 00000000000..7e0b2bec4b5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java @@ -0,0 +1,123 @@ +package org.openapitools.client.auth; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.util.Collections; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import okhttp3.*; +import okhttp3.Interceptor.Chain; +import okhttp3.Response.Builder; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.junit.Before; +import org.junit.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +public class RetryingOAuthTest { + + private RetryingOAuth oauth; + + @Before + public void setUp() throws Exception { + oauth = + new RetryingOAuth( + "_clientId", + "_clientSecret", + OAuthFlow.accessCode, + "https://token.example.com", + Collections.emptyMap()); + oauth.setAccessToken("expired-access-token"); + FieldUtils.writeField(oauth, "oAuthClient", mockOAuthClient(), true); + } + + @Test + public void testSingleRequestUnauthorized() throws Exception { + Response response = oauth.intercept(mockChain()); + assertEquals(HttpURLConnection.HTTP_OK, response.code()); + } + + @Test + public void testTwoConcurrentRequestsUnauthorized() throws Exception { + + Callable callable = + new Callable() { + @Override + public Response call() throws Exception { + return oauth.intercept(mockChain()); + } + }; + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future response1 = executor.submit(callable); + Future response2 = executor.submit(callable); + + assertEquals(HttpURLConnection.HTTP_OK, response1.get().code()); + assertEquals(HttpURLConnection.HTTP_OK, response2.get().code()); + } finally { + executor.shutdown(); + } + } + + private OAuthClient mockOAuthClient() throws OAuthProblemException, OAuthSystemException { + OAuthJSONAccessTokenResponse response = mock(OAuthJSONAccessTokenResponse.class); + when(response.getAccessToken()) + .thenAnswer( + new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + // sleep ensures that the bug is triggered. + Thread.sleep(1000); + return "new-access-token"; + } + }); + + OAuthClient client = mock(OAuthClient.class); + when(client.accessToken(any(OAuthClientRequest.class))).thenReturn(response); + return client; + } + + private Chain mockChain() throws IOException { + Chain chain = mock(Chain.class); + + final Request request = new Request.Builder().url("https://api.example.com").build(); + when(chain.request()).thenReturn(request); + + when(chain.proceed(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Response answer(InvocationOnMock inv) { + Request r = inv.getArgument(0); + int responseCode = + "Bearer new-access-token".equals(r.header("Authorization")) + ? HttpURLConnection.HTTP_OK + : HttpURLConnection.HTTP_UNAUTHORIZED; + return new Builder() + .protocol(Protocol.HTTP_1_0) + .message("sup") + .request(request) + .body( + ResponseBody.create( + new byte[0], + MediaType.get("application/test"))) + .code(responseCode) + .build(); + } + }); + + return chain; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java new file mode 100644 index 00000000000..ba387a41bf5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java @@ -0,0 +1,111 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for AdditionalPropertiesClass + */ +public class AdditionalPropertiesClassTest { + private final AdditionalPropertiesClass model = new AdditionalPropertiesClass(); + + /** + * Model tests for AdditionalPropertiesClass + */ + @Test + public void testAdditionalPropertiesClass() { + // TODO: test AdditionalPropertiesClass + } + + /** + * Test the property 'mapProperty' + */ + @Test + public void mapPropertyTest() { + // TODO: test mapProperty + } + + /** + * Test the property 'mapOfMapProperty' + */ + @Test + public void mapOfMapPropertyTest() { + // TODO: test mapOfMapProperty + } + + /** + * Test the property 'anytype1' + */ + @Test + public void anytype1Test() { + // TODO: test anytype1 + } + + /** + * Test the property 'mapWithUndeclaredPropertiesAnytype1' + */ + @Test + public void mapWithUndeclaredPropertiesAnytype1Test() { + // TODO: test mapWithUndeclaredPropertiesAnytype1 + } + + /** + * Test the property 'mapWithUndeclaredPropertiesAnytype2' + */ + @Test + public void mapWithUndeclaredPropertiesAnytype2Test() { + // TODO: test mapWithUndeclaredPropertiesAnytype2 + } + + /** + * Test the property 'mapWithUndeclaredPropertiesAnytype3' + */ + @Test + public void mapWithUndeclaredPropertiesAnytype3Test() { + // TODO: test mapWithUndeclaredPropertiesAnytype3 + } + + /** + * Test the property 'emptyMap' + */ + @Test + public void emptyMapTest() { + // TODO: test emptyMap + } + + /** + * Test the property 'mapWithUndeclaredPropertiesString' + */ + @Test + public void mapWithUndeclaredPropertiesStringTest() { + // TODO: test mapWithUndeclaredPropertiesString + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AnimalTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AnimalTest.java new file mode 100644 index 00000000000..b11ec766286 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AnimalTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Cat; +import org.openapitools.client.model.Dog; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Animal + */ +public class AnimalTest { + private final Animal model = new Animal(); + + /** + * Model tests for Animal + */ + @Test + public void testAnimal() { + // TODO: test Animal + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AppleReqTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AppleReqTest.java new file mode 100644 index 00000000000..9b071657eae --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AppleReqTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for AppleReq + */ +public class AppleReqTest { + private final AppleReq model = new AppleReq(); + + /** + * Model tests for AppleReq + */ + @Test + public void testAppleReq() { + // TODO: test AppleReq + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'mealy' + */ + @Test + public void mealyTest() { + // TODO: test mealy + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AppleTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AppleTest.java new file mode 100644 index 00000000000..d70d4bca5f9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/AppleTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Apple + */ +public class AppleTest { + private final Apple model = new Apple(); + + /** + * Model tests for Apple + */ + @Test + public void testApple() { + // TODO: test Apple + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'origin' + */ + @Test + public void originTest() { + // TODO: test origin + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java new file mode 100644 index 00000000000..9afc3397f46 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java @@ -0,0 +1,54 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ArrayOfNumberOnly + */ +public class ArrayOfNumberOnlyTest { + private final ArrayOfNumberOnly model = new ArrayOfNumberOnly(); + + /** + * Model tests for ArrayOfNumberOnly + */ + @Test + public void testArrayOfNumberOnly() { + // TODO: test ArrayOfNumberOnly + } + + /** + * Test the property 'arrayNumber' + */ + @Test + public void arrayNumberTest() { + // TODO: test arrayNumber + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ArrayTestTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ArrayTestTest.java new file mode 100644 index 00000000000..fab9a30565f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ArrayTestTest.java @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.ReadOnlyFirst; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ArrayTest + */ +public class ArrayTestTest { + private final ArrayTest model = new ArrayTest(); + + /** + * Model tests for ArrayTest + */ + @Test + public void testArrayTest() { + // TODO: test ArrayTest + } + + /** + * Test the property 'arrayOfString' + */ + @Test + public void arrayOfStringTest() { + // TODO: test arrayOfString + } + + /** + * Test the property 'arrayArrayOfInteger' + */ + @Test + public void arrayArrayOfIntegerTest() { + // TODO: test arrayArrayOfInteger + } + + /** + * Test the property 'arrayArrayOfModel' + */ + @Test + public void arrayArrayOfModelTest() { + // TODO: test arrayArrayOfModel + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BananaReqTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BananaReqTest.java new file mode 100644 index 00000000000..c1457da8700 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BananaReqTest.java @@ -0,0 +1,60 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for BananaReq + */ +public class BananaReqTest { + private final BananaReq model = new BananaReq(); + + /** + * Model tests for BananaReq + */ + @Test + public void testBananaReq() { + // TODO: test BananaReq + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + + /** + * Test the property 'sweet' + */ + @Test + public void sweetTest() { + // TODO: test sweet + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BananaTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BananaTest.java new file mode 100644 index 00000000000..ff0fbf231a7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BananaTest.java @@ -0,0 +1,52 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Banana + */ +public class BananaTest { + private final Banana model = new Banana(); + + /** + * Model tests for Banana + */ + @Test + public void testBanana() { + // TODO: test Banana + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BasquePigTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BasquePigTest.java new file mode 100644 index 00000000000..5aa6806a8f7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/BasquePigTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for BasquePig + */ +public class BasquePigTest { + private final BasquePig model = new BasquePig(); + + /** + * Model tests for BasquePig + */ + @Test + public void testBasquePig() { + // TODO: test BasquePig + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CapitalizationTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CapitalizationTest.java new file mode 100644 index 00000000000..ced4f48eb5f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CapitalizationTest.java @@ -0,0 +1,91 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Capitalization + */ +public class CapitalizationTest { + private final Capitalization model = new Capitalization(); + + /** + * Model tests for Capitalization + */ + @Test + public void testCapitalization() { + // TODO: test Capitalization + } + + /** + * Test the property 'smallCamel' + */ + @Test + public void smallCamelTest() { + // TODO: test smallCamel + } + + /** + * Test the property 'capitalCamel' + */ + @Test + public void capitalCamelTest() { + // TODO: test capitalCamel + } + + /** + * Test the property 'smallSnake' + */ + @Test + public void smallSnakeTest() { + // TODO: test smallSnake + } + + /** + * Test the property 'capitalSnake' + */ + @Test + public void capitalSnakeTest() { + // TODO: test capitalSnake + } + + /** + * Test the property 'scAETHFlowPoints' + */ + @Test + public void scAETHFlowPointsTest() { + // TODO: test scAETHFlowPoints + } + + /** + * Test the property 'ATT_NAME' + */ + @Test + public void ATT_NAMETest() { + // TODO: test ATT_NAME + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CatAllOfTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CatAllOfTest.java new file mode 100644 index 00000000000..384ab21b773 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CatAllOfTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for CatAllOf + */ +public class CatAllOfTest { + private final CatAllOf model = new CatAllOf(); + + /** + * Model tests for CatAllOf + */ + @Test + public void testCatAllOf() { + // TODO: test CatAllOf + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CatTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CatTest.java new file mode 100644 index 00000000000..b2b3e7e048d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CatTest.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Animal; +import org.openapitools.client.model.CatAllOf; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Cat + */ +public class CatTest { + private final Cat model = new Cat(); + + /** + * Model tests for Cat + */ + @Test + public void testCat() { + // TODO: test Cat + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'declawed' + */ + @Test + public void declawedTest() { + // TODO: test declawed + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CategoryTest.java new file mode 100644 index 00000000000..a6efa6e1fbc --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/CategoryTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ClassModelTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ClassModelTest.java new file mode 100644 index 00000000000..1233feec65e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ClassModelTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ClassModel + */ +public class ClassModelTest { + private final ClassModel model = new ClassModel(); + + /** + * Model tests for ClassModel + */ + @Test + public void testClassModel() { + // TODO: test ClassModel + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ClientTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ClientTest.java new file mode 100644 index 00000000000..456fab74c4d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ClientTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Client + */ +public class ClientTest { + private final Client model = new Client(); + + /** + * Model tests for Client + */ + @Test + public void testClient() { + // TODO: test Client + } + + /** + * Test the property 'client' + */ + @Test + public void clientTest() { + // TODO: test client + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java new file mode 100644 index 00000000000..2f8aa865194 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.QuadrilateralInterface; +import org.openapitools.client.model.ShapeInterface; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ComplexQuadrilateral + */ +public class ComplexQuadrilateralTest { + private final ComplexQuadrilateral model = new ComplexQuadrilateral(); + + /** + * Model tests for ComplexQuadrilateral + */ + @Test + public void testComplexQuadrilateral() { + // TODO: test ComplexQuadrilateral + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DanishPigTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DanishPigTest.java new file mode 100644 index 00000000000..459a6abf0f7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DanishPigTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for DanishPig + */ +public class DanishPigTest { + private final DanishPig model = new DanishPig(); + + /** + * Model tests for DanishPig + */ + @Test + public void testDanishPig() { + // TODO: test DanishPig + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java new file mode 100644 index 00000000000..9b3d2aee6a8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for DeprecatedObject + */ +public class DeprecatedObjectTest { + private final DeprecatedObject model = new DeprecatedObject(); + + /** + * Model tests for DeprecatedObject + */ + @Test + public void testDeprecatedObject() { + // TODO: test DeprecatedObject + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DogAllOfTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DogAllOfTest.java new file mode 100644 index 00000000000..0d695b15a63 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DogAllOfTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for DogAllOf + */ +public class DogAllOfTest { + private final DogAllOf model = new DogAllOf(); + + /** + * Model tests for DogAllOf + */ + @Test + public void testDogAllOf() { + // TODO: test DogAllOf + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DogTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DogTest.java new file mode 100644 index 00000000000..124bc99c1f1 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DogTest.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Animal; +import org.openapitools.client.model.DogAllOf; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Dog + */ +public class DogTest { + private final Dog model = new Dog(); + + /** + * Model tests for Dog + */ + @Test + public void testDog() { + // TODO: test Dog + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'breed' + */ + @Test + public void breedTest() { + // TODO: test breed + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DrawingTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DrawingTest.java new file mode 100644 index 00000000000..3e61e46812e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/DrawingTest.java @@ -0,0 +1,84 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.client.model.Fruit; +import org.openapitools.client.model.NullableShape; +import org.openapitools.client.model.Shape; +import org.openapitools.client.model.ShapeOrNull; +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Drawing + */ +public class DrawingTest { + private final Drawing model = new Drawing(); + + /** + * Model tests for Drawing + */ + @Test + public void testDrawing() { + // TODO: test Drawing + } + + /** + * Test the property 'mainShape' + */ + @Test + public void mainShapeTest() { + // TODO: test mainShape + } + + /** + * Test the property 'shapeOrNull' + */ + @Test + public void shapeOrNullTest() { + // TODO: test shapeOrNull + } + + /** + * Test the property 'nullableShape' + */ + @Test + public void nullableShapeTest() { + // TODO: test nullableShape + } + + /** + * Test the property 'shapes' + */ + @Test + public void shapesTest() { + // TODO: test shapes + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumArraysTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumArraysTest.java new file mode 100644 index 00000000000..c25b05e9f0d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumArraysTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for EnumArrays + */ +public class EnumArraysTest { + private final EnumArrays model = new EnumArrays(); + + /** + * Model tests for EnumArrays + */ + @Test + public void testEnumArrays() { + // TODO: test EnumArrays + } + + /** + * Test the property 'justSymbol' + */ + @Test + public void justSymbolTest() { + // TODO: test justSymbol + } + + /** + * Test the property 'arrayEnum' + */ + @Test + public void arrayEnumTest() { + // TODO: test arrayEnum + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumClassTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumClassTest.java new file mode 100644 index 00000000000..329454658e3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumClassTest.java @@ -0,0 +1,34 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.annotations.SerializedName; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for EnumClass + */ +public class EnumClassTest { + /** + * Model tests for EnumClass + */ + @Test + public void testEnumClass() { + // TODO: test EnumClass + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumTestTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumTestTest.java new file mode 100644 index 00000000000..54c181bf9f3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EnumTestTest.java @@ -0,0 +1,120 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.OuterEnum; +import org.openapitools.client.model.OuterEnumDefaultValue; +import org.openapitools.client.model.OuterEnumInteger; +import org.openapitools.client.model.OuterEnumIntegerDefaultValue; +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for EnumTest + */ +public class EnumTestTest { + private final EnumTest model = new EnumTest(); + + /** + * Model tests for EnumTest + */ + @Test + public void testEnumTest() { + // TODO: test EnumTest + } + + /** + * Test the property 'enumString' + */ + @Test + public void enumStringTest() { + // TODO: test enumString + } + + /** + * Test the property 'enumStringRequired' + */ + @Test + public void enumStringRequiredTest() { + // TODO: test enumStringRequired + } + + /** + * Test the property 'enumInteger' + */ + @Test + public void enumIntegerTest() { + // TODO: test enumInteger + } + + /** + * Test the property 'enumIntegerOnly' + */ + @Test + public void enumIntegerOnlyTest() { + // TODO: test enumIntegerOnly + } + + /** + * Test the property 'enumNumber' + */ + @Test + public void enumNumberTest() { + // TODO: test enumNumber + } + + /** + * Test the property 'outerEnum' + */ + @Test + public void outerEnumTest() { + // TODO: test outerEnum + } + + /** + * Test the property 'outerEnumInteger' + */ + @Test + public void outerEnumIntegerTest() { + // TODO: test outerEnumInteger + } + + /** + * Test the property 'outerEnumDefaultValue' + */ + @Test + public void outerEnumDefaultValueTest() { + // TODO: test outerEnumDefaultValue + } + + /** + * Test the property 'outerEnumIntegerDefaultValue' + */ + @Test + public void outerEnumIntegerDefaultValueTest() { + // TODO: test outerEnumIntegerDefaultValue + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java new file mode 100644 index 00000000000..f3bae7cd78b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ShapeInterface; +import org.openapitools.client.model.TriangleInterface; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for EquilateralTriangle + */ +public class EquilateralTriangleTest { + private final EquilateralTriangle model = new EquilateralTriangle(); + + /** + * Model tests for EquilateralTriangle + */ + @Test + public void testEquilateralTriangle() { + // TODO: test EquilateralTriangle + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java new file mode 100644 index 00000000000..0ca36621208 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for FileSchemaTestClass + */ +public class FileSchemaTestClassTest { + private final FileSchemaTestClass model = new FileSchemaTestClass(); + + /** + * Model tests for FileSchemaTestClass + */ + @Test + public void testFileSchemaTestClass() { + // TODO: test FileSchemaTestClass + } + + /** + * Test the property 'file' + */ + @Test + public void fileTest() { + // TODO: test file + } + + /** + * Test the property 'files' + */ + @Test + public void filesTest() { + // TODO: test files + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FooTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FooTest.java new file mode 100644 index 00000000000..417b05ea7fa --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FooTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Foo + */ +public class FooTest { + private final Foo model = new Foo(); + + /** + * Model tests for Foo + */ + @Test + public void testFoo() { + // TODO: test Foo + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FormatTestTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FormatTestTest.java new file mode 100644 index 00000000000..6d3c5e1c2a8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FormatTestTest.java @@ -0,0 +1,176 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.File; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.UUID; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for FormatTest + */ +public class FormatTestTest { + private final FormatTest model = new FormatTest(); + + /** + * Model tests for FormatTest + */ + @Test + public void testFormatTest() { + // TODO: test FormatTest + } + + /** + * Test the property 'integer' + */ + @Test + public void integerTest() { + // TODO: test integer + } + + /** + * Test the property 'int32' + */ + @Test + public void int32Test() { + // TODO: test int32 + } + + /** + * Test the property 'int64' + */ + @Test + public void int64Test() { + // TODO: test int64 + } + + /** + * Test the property 'number' + */ + @Test + public void numberTest() { + // TODO: test number + } + + /** + * Test the property '_float' + */ + @Test + public void _floatTest() { + // TODO: test _float + } + + /** + * Test the property '_double' + */ + @Test + public void _doubleTest() { + // TODO: test _double + } + + /** + * Test the property 'decimal' + */ + @Test + public void decimalTest() { + // TODO: test decimal + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + + /** + * Test the property '_byte' + */ + @Test + public void _byteTest() { + // TODO: test _byte + } + + /** + * Test the property 'binary' + */ + @Test + public void binaryTest() { + // TODO: test binary + } + + /** + * Test the property 'date' + */ + @Test + public void dateTest() { + // TODO: test date + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'patternWithDigits' + */ + @Test + public void patternWithDigitsTest() { + // TODO: test patternWithDigits + } + + /** + * Test the property 'patternWithDigitsAndDelimiter' + */ + @Test + public void patternWithDigitsAndDelimiterTest() { + // TODO: test patternWithDigitsAndDelimiter + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FruitReqTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FruitReqTest.java new file mode 100644 index 00000000000..d279752b095 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FruitReqTest.java @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.openapitools.client.model.AppleReq; +import org.openapitools.client.model.BananaReq; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for FruitReq + */ +public class FruitReqTest { + private final FruitReq model = new FruitReq(); + + /** + * Model tests for FruitReq + */ + @Test + public void testFruitReq() { + // TODO: test FruitReq + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'mealy' + */ + @Test + public void mealyTest() { + // TODO: test mealy + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + + /** + * Test the property 'sweet' + */ + @Test + public void sweetTest() { + // TODO: test sweet + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FruitTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FruitTest.java new file mode 100644 index 00000000000..b9e1f8af86c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/FruitTest.java @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.openapitools.client.model.Apple; +import org.openapitools.client.model.Banana; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Fruit + */ +public class FruitTest { + private final Fruit model = new Fruit(); + + /** + * Model tests for Fruit + */ + @Test + public void testFruit() { + // TODO: test Fruit + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'origin' + */ + @Test + public void originTest() { + // TODO: test origin + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/GmFruitTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/GmFruitTest.java new file mode 100644 index 00000000000..cd93334d89f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/GmFruitTest.java @@ -0,0 +1,70 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.openapitools.client.model.Apple; +import org.openapitools.client.model.Banana; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for GmFruit + */ +public class GmFruitTest { + private final GmFruit model = new GmFruit(); + + /** + * Model tests for GmFruit + */ + @Test + public void testGmFruit() { + // TODO: test GmFruit + } + + /** + * Test the property 'cultivar' + */ + @Test + public void cultivarTest() { + // TODO: test cultivar + } + + /** + * Test the property 'origin' + */ + @Test + public void originTest() { + // TODO: test origin + } + + /** + * Test the property 'lengthCm' + */ + @Test + public void lengthCmTest() { + // TODO: test lengthCm + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java new file mode 100644 index 00000000000..63221458573 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java @@ -0,0 +1,52 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ParentPet; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for GrandparentAnimal + */ +public class GrandparentAnimalTest { + private final GrandparentAnimal model = new GrandparentAnimal(); + + /** + * Model tests for GrandparentAnimal + */ + @Test + public void testGrandparentAnimal() { + // TODO: test GrandparentAnimal + } + + /** + * Test the property 'petType' + */ + @Test + public void petTypeTest() { + // TODO: test petType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java new file mode 100644 index 00000000000..0272d7b8000 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for HasOnlyReadOnly + */ +public class HasOnlyReadOnlyTest { + private final HasOnlyReadOnly model = new HasOnlyReadOnly(); + + /** + * Model tests for HasOnlyReadOnly + */ + @Test + public void testHasOnlyReadOnly() { + // TODO: test HasOnlyReadOnly + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'foo' + */ + @Test + public void fooTest() { + // TODO: test foo + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java new file mode 100644 index 00000000000..11572abcf30 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java @@ -0,0 +1,52 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for HealthCheckResult + */ +public class HealthCheckResultTest { + private final HealthCheckResult model = new HealthCheckResult(); + + /** + * Model tests for HealthCheckResult + */ + @Test + public void testHealthCheckResult() { + // TODO: test HealthCheckResult + } + + /** + * Test the property 'nullableMessage' + */ + @Test + public void nullableMessageTest() { + // TODO: test nullableMessage + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/InlineResponseDefaultTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/InlineResponseDefaultTest.java new file mode 100644 index 00000000000..58831cea0bd --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/InlineResponseDefaultTest.java @@ -0,0 +1,52 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Foo; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for InlineResponseDefault + */ +public class InlineResponseDefaultTest { + private final InlineResponseDefault model = new InlineResponseDefault(); + + /** + * Model tests for InlineResponseDefault + */ + @Test + public void testInlineResponseDefault() { + // TODO: test InlineResponseDefault + } + + /** + * Test the property 'string' + */ + @Test + public void stringTest() { + // TODO: test string + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java new file mode 100644 index 00000000000..2f21d3e37c7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ShapeInterface; +import org.openapitools.client.model.TriangleInterface; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for IsoscelesTriangle + */ +public class IsoscelesTriangleTest { + private final IsoscelesTriangle model = new IsoscelesTriangle(); + + /** + * Model tests for IsoscelesTriangle + */ + @Test + public void testIsoscelesTriangle() { + // TODO: test IsoscelesTriangle + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MammalTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MammalTest.java new file mode 100644 index 00000000000..531d9b28688 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MammalTest.java @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Pig; +import org.openapitools.client.model.Whale; +import org.openapitools.client.model.Zebra; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Mammal + */ +public class MammalTest { + private final Mammal model = new Mammal(); + + /** + * Model tests for Mammal + */ + @Test + public void testMammal() { + // TODO: test Mammal + } + + /** + * Test the property 'hasBaleen' + */ + @Test + public void hasBaleenTest() { + // TODO: test hasBaleen + } + + /** + * Test the property 'hasTeeth' + */ + @Test + public void hasTeethTest() { + // TODO: test hasTeeth + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MapTestTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MapTestTest.java new file mode 100644 index 00000000000..f86a1303fc8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MapTestTest.java @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for MapTest + */ +public class MapTestTest { + private final MapTest model = new MapTest(); + + /** + * Model tests for MapTest + */ + @Test + public void testMapTest() { + // TODO: test MapTest + } + + /** + * Test the property 'mapMapOfString' + */ + @Test + public void mapMapOfStringTest() { + // TODO: test mapMapOfString + } + + /** + * Test the property 'mapOfEnumString' + */ + @Test + public void mapOfEnumStringTest() { + // TODO: test mapOfEnumString + } + + /** + * Test the property 'directMap' + */ + @Test + public void directMapTest() { + // TODO: test directMap + } + + /** + * Test the property 'indirectMap' + */ + @Test + public void indirectMapTest() { + // TODO: test indirectMap + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java new file mode 100644 index 00000000000..808773a5d85 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java @@ -0,0 +1,73 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import org.openapitools.client.model.Animal; +import org.threeten.bp.OffsetDateTime; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ +public class MixedPropertiesAndAdditionalPropertiesClassTest { + private final MixedPropertiesAndAdditionalPropertiesClass model = new MixedPropertiesAndAdditionalPropertiesClass(); + + /** + * Model tests for MixedPropertiesAndAdditionalPropertiesClass + */ + @Test + public void testMixedPropertiesAndAdditionalPropertiesClass() { + // TODO: test MixedPropertiesAndAdditionalPropertiesClass + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'dateTime' + */ + @Test + public void dateTimeTest() { + // TODO: test dateTime + } + + /** + * Test the property 'map' + */ + @Test + public void mapTest() { + // TODO: test map + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/Model200ResponseTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/Model200ResponseTest.java new file mode 100644 index 00000000000..d81fa5a0f66 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/Model200ResponseTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Model200Response + */ +public class Model200ResponseTest { + private final Model200Response model = new Model200Response(); + + /** + * Model tests for Model200Response + */ + @Test + public void testModel200Response() { + // TODO: test Model200Response + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'propertyClass' + */ + @Test + public void propertyClassTest() { + // TODO: test propertyClass + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java new file mode 100644 index 00000000000..91bd8fada26 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java @@ -0,0 +1,67 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ModelReturnTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ModelReturnTest.java new file mode 100644 index 00000000000..f317fef485e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ModelReturnTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ModelReturn + */ +public class ModelReturnTest { + private final ModelReturn model = new ModelReturn(); + + /** + * Model tests for ModelReturn + */ + @Test + public void testModelReturn() { + // TODO: test ModelReturn + } + + /** + * Test the property '_return' + */ + @Test + public void _returnTest() { + // TODO: test _return + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NameTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NameTest.java new file mode 100644 index 00000000000..1ed41a0f80c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NameTest.java @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Name + */ +public class NameTest { + private final Name model = new Name(); + + /** + * Model tests for Name + */ + @Test + public void testName() { + // TODO: test Name + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'snakeCase' + */ + @Test + public void snakeCaseTest() { + // TODO: test snakeCase + } + + /** + * Test the property 'property' + */ + @Test + public void propertyTest() { + // TODO: test property + } + + /** + * Test the property '_123number' + */ + @Test + public void _123numberTest() { + // TODO: test _123number + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NullableClassTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NullableClassTest.java new file mode 100644 index 00000000000..74c390c8a66 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NullableClassTest.java @@ -0,0 +1,147 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.openapitools.jackson.nullable.JsonNullable; +import org.threeten.bp.LocalDate; +import org.threeten.bp.OffsetDateTime; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for NullableClass + */ +public class NullableClassTest { + private final NullableClass model = new NullableClass(); + + /** + * Model tests for NullableClass + */ + @Test + public void testNullableClass() { + // TODO: test NullableClass + } + + /** + * Test the property 'integerProp' + */ + @Test + public void integerPropTest() { + // TODO: test integerProp + } + + /** + * Test the property 'numberProp' + */ + @Test + public void numberPropTest() { + // TODO: test numberProp + } + + /** + * Test the property 'booleanProp' + */ + @Test + public void booleanPropTest() { + // TODO: test booleanProp + } + + /** + * Test the property 'stringProp' + */ + @Test + public void stringPropTest() { + // TODO: test stringProp + } + + /** + * Test the property 'dateProp' + */ + @Test + public void datePropTest() { + // TODO: test dateProp + } + + /** + * Test the property 'datetimeProp' + */ + @Test + public void datetimePropTest() { + // TODO: test datetimeProp + } + + /** + * Test the property 'arrayNullableProp' + */ + @Test + public void arrayNullablePropTest() { + // TODO: test arrayNullableProp + } + + /** + * Test the property 'arrayAndItemsNullableProp' + */ + @Test + public void arrayAndItemsNullablePropTest() { + // TODO: test arrayAndItemsNullableProp + } + + /** + * Test the property 'arrayItemsNullable' + */ + @Test + public void arrayItemsNullableTest() { + // TODO: test arrayItemsNullable + } + + /** + * Test the property 'objectNullableProp' + */ + @Test + public void objectNullablePropTest() { + // TODO: test objectNullableProp + } + + /** + * Test the property 'objectAndItemsNullableProp' + */ + @Test + public void objectAndItemsNullablePropTest() { + // TODO: test objectAndItemsNullableProp + } + + /** + * Test the property 'objectItemsNullable' + */ + @Test + public void objectItemsNullableTest() { + // TODO: test objectItemsNullable + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NullableShapeTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NullableShapeTest.java new file mode 100644 index 00000000000..d6c946fff37 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NullableShapeTest.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Quadrilateral; +import org.openapitools.client.model.Triangle; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for NullableShape + */ +public class NullableShapeTest { + private final NullableShape model = new NullableShape(); + + /** + * Model tests for NullableShape + */ + @Test + public void testNullableShape() { + // TODO: test NullableShape + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NumberOnlyTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NumberOnlyTest.java new file mode 100644 index 00000000000..15b74f7ef8b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/NumberOnlyTest.java @@ -0,0 +1,52 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for NumberOnly + */ +public class NumberOnlyTest { + private final NumberOnly model = new NumberOnly(); + + /** + * Model tests for NumberOnly + */ + @Test + public void testNumberOnly() { + // TODO: test NumberOnly + } + + /** + * Test the property 'justNumber' + */ + @Test + public void justNumberTest() { + // TODO: test justNumber + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java new file mode 100644 index 00000000000..f8403d9abc4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java @@ -0,0 +1,79 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.DeprecatedObject; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ObjectWithDeprecatedFields + */ +public class ObjectWithDeprecatedFieldsTest { + private final ObjectWithDeprecatedFields model = new ObjectWithDeprecatedFields(); + + /** + * Model tests for ObjectWithDeprecatedFields + */ + @Test + public void testObjectWithDeprecatedFields() { + // TODO: test ObjectWithDeprecatedFields + } + + /** + * Test the property 'uuid' + */ + @Test + public void uuidTest() { + // TODO: test uuid + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'deprecatedRef' + */ + @Test + public void deprecatedRefTest() { + // TODO: test deprecatedRef + } + + /** + * Test the property 'bars' + */ + @Test + public void barsTest() { + // TODO: test bars + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OrderTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OrderTest.java new file mode 100644 index 00000000000..b5cc55e4f58 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OrderTest.java @@ -0,0 +1,92 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.threeten.bp.OffsetDateTime; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterCompositeTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterCompositeTest.java new file mode 100644 index 00000000000..67ee5996363 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterCompositeTest.java @@ -0,0 +1,68 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.math.BigDecimal; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for OuterComposite + */ +public class OuterCompositeTest { + private final OuterComposite model = new OuterComposite(); + + /** + * Model tests for OuterComposite + */ + @Test + public void testOuterComposite() { + // TODO: test OuterComposite + } + + /** + * Test the property 'myNumber' + */ + @Test + public void myNumberTest() { + // TODO: test myNumber + } + + /** + * Test the property 'myString' + */ + @Test + public void myStringTest() { + // TODO: test myString + } + + /** + * Test the property 'myBoolean' + */ + @Test + public void myBooleanTest() { + // TODO: test myBoolean + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java new file mode 100644 index 00000000000..e6d40222de0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java @@ -0,0 +1,34 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.annotations.SerializedName; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for OuterEnumDefaultValue + */ +public class OuterEnumDefaultValueTest { + /** + * Model tests for OuterEnumDefaultValue + */ + @Test + public void testOuterEnumDefaultValue() { + // TODO: test OuterEnumDefaultValue + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java new file mode 100644 index 00000000000..c030716b561 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java @@ -0,0 +1,34 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.annotations.SerializedName; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for OuterEnumIntegerDefaultValue + */ +public class OuterEnumIntegerDefaultValueTest { + /** + * Model tests for OuterEnumIntegerDefaultValue + */ + @Test + public void testOuterEnumIntegerDefaultValue() { + // TODO: test OuterEnumIntegerDefaultValue + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java new file mode 100644 index 00000000000..67b2f5ede6d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java @@ -0,0 +1,34 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.annotations.SerializedName; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for OuterEnumInteger + */ +public class OuterEnumIntegerTest { + /** + * Model tests for OuterEnumInteger + */ + @Test + public void testOuterEnumInteger() { + // TODO: test OuterEnumInteger + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumTest.java new file mode 100644 index 00000000000..220d40e83cb --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/OuterEnumTest.java @@ -0,0 +1,34 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.annotations.SerializedName; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for OuterEnum + */ +public class OuterEnumTest { + /** + * Model tests for OuterEnum + */ + @Test + public void testOuterEnum() { + // TODO: test OuterEnum + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ParentPetTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ParentPetTest.java new file mode 100644 index 00000000000..729352ddf64 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ParentPetTest.java @@ -0,0 +1,52 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.GrandparentAnimal; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ParentPet + */ +public class ParentPetTest { + private final ParentPet model = new ParentPet(); + + /** + * Model tests for ParentPet + */ + @Test + public void testParentPet() { + // TODO: test ParentPet + } + + /** + * Test the property 'petType' + */ + @Test + public void petTypeTest() { + // TODO: test petType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/PigTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/PigTest.java new file mode 100644 index 00000000000..003af60bcc4 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/PigTest.java @@ -0,0 +1,53 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.BasquePig; +import org.openapitools.client.model.DanishPig; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Pig + */ +public class PigTest { + private final Pig model = new Pig(); + + /** + * Model tests for Pig + */ + @Test + public void testPig() { + // TODO: test Pig + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java new file mode 100644 index 00000000000..a27f30704af --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for QuadrilateralInterface + */ +public class QuadrilateralInterfaceTest { + private final QuadrilateralInterface model = new QuadrilateralInterface(); + + /** + * Model tests for QuadrilateralInterface + */ + @Test + public void testQuadrilateralInterface() { + // TODO: test QuadrilateralInterface + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/QuadrilateralTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/QuadrilateralTest.java new file mode 100644 index 00000000000..96985f4b6f5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/QuadrilateralTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ComplexQuadrilateral; +import org.openapitools.client.model.SimpleQuadrilateral; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Quadrilateral + */ +public class QuadrilateralTest { + private final Quadrilateral model = new Quadrilateral(); + + /** + * Model tests for Quadrilateral + */ + @Test + public void testQuadrilateral() { + // TODO: test Quadrilateral + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java new file mode 100644 index 00000000000..2dc9cb2ae2c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ReadOnlyFirst + */ +public class ReadOnlyFirstTest { + private final ReadOnlyFirst model = new ReadOnlyFirst(); + + /** + * Model tests for ReadOnlyFirst + */ + @Test + public void testReadOnlyFirst() { + // TODO: test ReadOnlyFirst + } + + /** + * Test the property 'bar' + */ + @Test + public void barTest() { + // TODO: test bar + } + + /** + * Test the property 'baz' + */ + @Test + public void bazTest() { + // TODO: test baz + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java new file mode 100644 index 00000000000..62bfbaa7d72 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.ShapeInterface; +import org.openapitools.client.model.TriangleInterface; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ScaleneTriangle + */ +public class ScaleneTriangleTest { + private final ScaleneTriangle model = new ScaleneTriangle(); + + /** + * Model tests for ScaleneTriangle + */ + @Test + public void testScaleneTriangle() { + // TODO: test ScaleneTriangle + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java new file mode 100644 index 00000000000..21b9d747885 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ShapeInterface + */ +public class ShapeInterfaceTest { + private final ShapeInterface model = new ShapeInterface(); + + /** + * Model tests for ShapeInterface + */ + @Test + public void testShapeInterface() { + // TODO: test ShapeInterface + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java new file mode 100644 index 00000000000..9ea2ec9fa04 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Quadrilateral; +import org.openapitools.client.model.Triangle; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for ShapeOrNull + */ +public class ShapeOrNullTest { + private final ShapeOrNull model = new ShapeOrNull(); + + /** + * Model tests for ShapeOrNull + */ + @Test + public void testShapeOrNull() { + // TODO: test ShapeOrNull + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeTest.java new file mode 100644 index 00000000000..1ed82e64e36 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ShapeTest.java @@ -0,0 +1,69 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.Quadrilateral; +import org.openapitools.client.model.Triangle; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Shape + */ +public class ShapeTest { + private final Shape model = new Shape(); + + /** + * Model tests for Shape + */ + @Test + public void testShape() { + // TODO: test Shape + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java new file mode 100644 index 00000000000..7396def4a46 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.QuadrilateralInterface; +import org.openapitools.client.model.ShapeInterface; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for SimpleQuadrilateral + */ +public class SimpleQuadrilateralTest { + private final SimpleQuadrilateral model = new SimpleQuadrilateral(); + + /** + * Model tests for SimpleQuadrilateral + */ + @Test + public void testSimpleQuadrilateral() { + // TODO: test SimpleQuadrilateral + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'quadrilateralType' + */ + @Test + public void quadrilateralTypeTest() { + // TODO: test quadrilateralType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java new file mode 100644 index 00000000000..0c723c8cd0c --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for SpecialModelName + */ +public class SpecialModelNameTest { + private final SpecialModelName model = new SpecialModelName(); + + /** + * Model tests for SpecialModelName + */ + @Test + public void testSpecialModelName() { + // TODO: test SpecialModelName + } + + /** + * Test the property '$specialPropertyName' + */ + @Test + public void $specialPropertyNameTest() { + // TODO: test $specialPropertyName + } + + /** + * Test the property 'specialModelName' + */ + @Test + public void specialModelNameTest() { + // TODO: test specialModelName + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TagTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TagTest.java new file mode 100644 index 00000000000..83f536d2fa3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TagTest.java @@ -0,0 +1,59 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java new file mode 100644 index 00000000000..e17fdd94cf2 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for TriangleInterface + */ +public class TriangleInterfaceTest { + private final TriangleInterface model = new TriangleInterface(); + + /** + * Model tests for TriangleInterface + */ + @Test + public void testTriangleInterface() { + // TODO: test TriangleInterface + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TriangleTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TriangleTest.java new file mode 100644 index 00000000000..071646b6645 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/TriangleTest.java @@ -0,0 +1,62 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.client.model.EquilateralTriangle; +import org.openapitools.client.model.IsoscelesTriangle; +import org.openapitools.client.model.ScaleneTriangle; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Triangle + */ +public class TriangleTest { + private final Triangle model = new Triangle(); + + /** + * Model tests for Triangle + */ + @Test + public void testTriangle() { + // TODO: test Triangle + } + + /** + * Test the property 'shapeType' + */ + @Test + public void shapeTypeTest() { + // TODO: test shapeType + } + + /** + * Test the property 'triangleType' + */ + @Test + public void triangleTypeTest() { + // TODO: test triangleType + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/UserTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/UserTest.java new file mode 100644 index 00000000000..3b673daf544 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/UserTest.java @@ -0,0 +1,140 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + + /** + * Test the property 'objectWithNoDeclaredProps' + */ + @Test + public void objectWithNoDeclaredPropsTest() { + // TODO: test objectWithNoDeclaredProps + } + + /** + * Test the property 'objectWithNoDeclaredPropsNullable' + */ + @Test + public void objectWithNoDeclaredPropsNullableTest() { + // TODO: test objectWithNoDeclaredPropsNullable + } + + /** + * Test the property 'anyTypeProp' + */ + @Test + public void anyTypePropTest() { + // TODO: test anyTypeProp + } + + /** + * Test the property 'anyTypePropNullable' + */ + @Test + public void anyTypePropNullableTest() { + // TODO: test anyTypePropNullable + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/WhaleTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/WhaleTest.java new file mode 100644 index 00000000000..6b38ea184bb --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/WhaleTest.java @@ -0,0 +1,67 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Whale + */ +public class WhaleTest { + private final Whale model = new Whale(); + + /** + * Model tests for Whale + */ + @Test + public void testWhale() { + // TODO: test Whale + } + + /** + * Test the property 'hasBaleen' + */ + @Test + public void hasBaleenTest() { + // TODO: test hasBaleen + } + + /** + * Test the property 'hasTeeth' + */ + @Test + public void hasTeethTest() { + // TODO: test hasTeeth + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ZebraTest.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ZebraTest.java new file mode 100644 index 00000000000..b622d7822bf --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/test/java/org/openapitools/client/model/ZebraTest.java @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import io.swagger.annotations.ApiModel; +import io.swagger.annotations.ApiModelProperty; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + + +/** + * Model tests for Zebra + */ +public class ZebraTest { + private final Zebra model = new Zebra(); + + /** + * Model tests for Zebra + */ + @Test + public void testZebra() { + // TODO: test Zebra + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'className' + */ + @Test + public void classNameTest() { + // TODO: test className + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java new file mode 100644 index 00000000000..ddda27d5fed --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -0,0 +1,149 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.openapitools.client.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 nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + + +} From a24d314006c5d19c600d089a3d1c4648f7e39f69 Mon Sep 17 00:00:00 2001 From: Fumito Nakazawa Date: Wed, 1 Dec 2021 01:34:15 +0900 Subject: [PATCH 40/61] [swift5] Use enum as parameter instead of raw type (#10967) * Fix enum type * Remove operation_id * Fix samples --- .../src/main/resources/swift5/api.mustache | 14 +++++++------- .../src/main/resources/swift5/api_doc.mustache | 8 ++++---- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../swift5/alamofireLibrary/docs/FakeAPI.md | 2 +- .../swift5/alamofireLibrary/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../swift5/asyncAwaitLibrary/docs/FakeAPI.md | 2 +- .../swift5/asyncAwaitLibrary/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../petstore/swift5/combineLibrary/docs/FakeAPI.md | 2 +- .../petstore/swift5/combineLibrary/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../client/petstore/swift5/default/docs/FakeAPI.md | 2 +- .../client/petstore/swift5/default/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../petstore/swift5/deprecated/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../petstore/swift5/nonPublicApi/docs/FakeAPI.md | 2 +- .../petstore/swift5/nonPublicApi/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../petstore/swift5/objcCompatible/docs/FakeAPI.md | 2 +- .../petstore/swift5/objcCompatible/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../swift5/promisekitLibrary/docs/FakeAPI.md | 2 +- .../swift5/promisekitLibrary/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../swift5/readonlyProperties/docs/FakeAPI.md | 2 +- .../swift5/readonlyProperties/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../petstore/swift5/resultLibrary/docs/FakeAPI.md | 2 +- .../petstore/swift5/resultLibrary/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../petstore/swift5/rxswiftLibrary/docs/FakeAPI.md | 2 +- .../petstore/swift5/rxswiftLibrary/docs/PetAPI.md | 2 +- .../Sources/PetstoreClient/APIs/FakeAPI.swift | 4 ++-- .../Sources/PetstoreClient/APIs/PetAPI.swift | 4 ++-- .../swift5/urlsessionLibrary/docs/FakeAPI.md | 2 +- .../swift5/urlsessionLibrary/docs/PetAPI.md | 2 +- .../petstore/swift5/vaporLibrary/docs/FakeAPI.md | 2 +- .../petstore/swift5/vaporLibrary/docs/PetAPI.md | 2 +- .../Classes/OpenAPIs/APIs/FakeAPI.swift | 4 ++-- .../Classes/OpenAPIs/APIs/PetAPI.swift | 4 ++-- .../swift5/x-swift-hashable/docs/FakeAPI.md | 2 +- .../swift5/x-swift-hashable/docs/PetAPI.md | 2 +- 54 files changed, 88 insertions(+), 88 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/swift5/api.mustache b/modules/openapi-generator/src/main/resources/swift5/api.mustache index 6e95e653a32..42b44955aad 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api.mustache @@ -57,7 +57,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @discardableResult - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)) -> URLSessionTask? { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void)) -> URLSessionTask? { return {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in switch result { {{#returnType}} @@ -91,7 +91,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { let deferred = Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}>.pending() {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in switch result { @@ -122,7 +122,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Observable<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> Observable<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { return Observable.create { observer -> Disposable in let task = {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in switch result { @@ -160,7 +160,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> AnyPublisher<{{{returnType}}}{{^returnType}}Void{{/returnType}}, Error> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) -> AnyPublisher<{{{returnType}}}{{^returnType}}Void{{/returnType}}, Error> { var task: URLSessionTask? return Future<{{{returnType}}}{{^returnType}}Void{{/returnType}}, Error> { promise in task = {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in @@ -198,7 +198,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) async throws{{#returnType}} -> {{{returnType}}}{{/returnType}} { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue) async throws{{#returnType}} -> {{{returnType}}}{{/returnType}} { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() @@ -241,7 +241,7 @@ extension {{projectName}}API { @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} @discardableResult - open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<{{{returnType}}}{{^returnType}}Void{{/returnType}}, ErrorResponse>) -> Void)) -> URLSessionTask? { + open class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}apiResponseQueue: DispatchQueue = {{projectName}}API.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<{{{returnType}}}{{^returnType}}Void{{/returnType}}, ErrorResponse>) -> Void)) -> URLSessionTask? { return {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}).execute(apiResponseQueue) { result in switch result { {{#returnType}} @@ -411,7 +411,7 @@ extension {{projectName}}API { {{#isDeprecated}} @available(*, deprecated, message: "This operation is deprecated.") {{/isDeprecated}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> RequestBuilder<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}WithRequestBuilder({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> RequestBuilder<{{{returnType}}}{{^returnType}}Void{{/returnType}}> { {{^pathParams}}let{{/pathParams}}{{#pathParams}}{{#-first}}var{{/-first}}{{/pathParams}} localVariablePath = "{{{path}}}"{{#pathParams}} let {{paramName}}PreEscape = "\({{#isEnum}}{{paramName}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}.rawValue{{/isContainer}}{{/isEnum}}{{^isEnum}}APIHelper.mapValueToPathItem({{paramName}}){{/isEnum}})" let {{paramName}}PostEscape = {{paramName}}PreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" diff --git a/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache b/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache index 7d7c58f1dc4..7faccc1a1d8 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api_doc.mustache @@ -15,18 +15,18 @@ Method | HTTP request | Description {{^usePromiseKit}} {{^useRxSwift}} {{^useVapor}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping (_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void) + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}completion: @escaping (_ data: {{{returnType}}}{{^returnType}}Void{{/returnType}}?, _ error: Error?) -> Void) {{/useVapor}} {{/useRxSwift}} {{/usePromiseKit}} {{#usePromiseKit}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}> + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}} {{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Promise<{{{returnType}}}{{^returnType}}Void{{/returnType}}> {{/usePromiseKit}} {{#useRxSwift}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Observable<{{{returnType}}}{{^returnType}}Void{{/returnType}}> + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) -> Observable<{{{returnType}}}{{^returnType}}Void{{/returnType}}> {{/useRxSwift}} {{#useVapor}} - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}{{{dataType}}}{{/isContainer}}{{^isContainer}}{{{datatypeWithEnum}}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}API.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}> + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}open{{/nonPublicApi}} class func {{operationId}}({{#allParams}}{{paramName}}: {{#isEnum}}{{#isContainer}}[{{enumName}}_{{operationId}}]{{/isContainer}}{{^isContainer}}{{enumName}}_{{operationId}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}? = nil{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#hasParams}}, {{/hasParams}}headers: HTTPHeaders = {{projectName}}API.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture<{{#lambda.titlecase}}{{operationId}}{{/lambda.titlecase}}> {{/useVapor}} ``` diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 87d1539d825..a5165719f10 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5c22a59a5c5..bd5c091925b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/alamofireLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index e773584bb02..8e449d22dc7 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -589,7 +589,7 @@ open class FakeAPI { - returns: Void */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() @@ -627,7 +627,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 2f713417bfb..f169ed382da 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -152,7 +152,7 @@ open class PetAPI { - returns: [Pet] */ @available(macOS 12.0, iOS 15.0, watchOS 8.0, tvOS 15.0, *) - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws -> [Pet] { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) async throws -> [Pet] { var task: URLSessionTask? return try await withTaskCancellationHandler { try Task.checkCancellation() @@ -186,7 +186,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index b64f5581ea6..27b455e59ff 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -561,7 +561,7 @@ open class FakeAPI { */ #if canImport(Combine) @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher { var task: URLSessionTask? return Future { promise in task = testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in @@ -594,7 +594,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 1335065e013..71225a5b53d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -148,7 +148,7 @@ open class PetAPI { */ #if canImport(Combine) @available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[Pet], Error> { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> AnyPublisher<[Pet], Error> { var task: URLSessionTask? return Future<[Pet], Error> { promise in task = findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in @@ -177,7 +177,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/combineLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index faaa1611c8f..bf154f2e1db 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -529,7 +529,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -554,7 +554,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 87aedd5c1a3..655b2358c52 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/default/docs/FakeAPI.md b/samples/client/petstore/swift5/default/docs/FakeAPI.md index e2df98a9d44..5004221689e 100644 --- a/samples/client/petstore/swift5/default/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/default/docs/FakeAPI.md @@ -492,7 +492,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/default/docs/PetAPI.md b/samples/client/petstore/swift5/default/docs/PetAPI.md index 6195924f3c2..ee837e6f8af 100644 --- a/samples/client/petstore/swift5/default/docs/PetAPI.md +++ b/samples/client/petstore/swift5/default/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index f838ced0df6..59a82575aa1 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/deprecated/docs/PetAPI.md b/samples/client/petstore/swift5/deprecated/docs/PetAPI.md index c602c9fb572..cd138421072 100644 --- a/samples/client/petstore/swift5/deprecated/docs/PetAPI.md +++ b/samples/client/petstore/swift5/deprecated/docs/PetAPI.md @@ -114,7 +114,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index a5bf5a193ef..31c875915ac 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ internal class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + internal class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ internal class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - internal class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + internal class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 0441d91c094..74aa56a14e6 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ internal class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - internal class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + internal class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ internal class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - internal class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + internal class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md index d18c9425010..1cc75c5aab2 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - internal class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + internal class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md b/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md index eb2db2040cd..a9e13c339cf 100644 --- a/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md +++ b/samples/client/petstore/swift5/nonPublicApi/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - internal class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + internal class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 58208b46ee7..5396fe8dd32 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ import AnyCodable - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ import AnyCodable - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 6ee48721751..58fbeae4d63 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ import AnyCodable - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ import AnyCodable - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md index c0a0824fb70..a75c5864f1c 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md b/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md index b3187a51128..5e6bccd7eaa 100644 --- a/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md +++ b/samples/client/petstore/swift5/objcCompatible/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index ef784bfffdc..17beed78a8e 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -493,7 +493,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise */ - open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { + open class func testEnumParameters( enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise { let deferred = Promise.pending() testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { @@ -520,7 +520,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index a6de43f3870..11c84c86433 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -128,7 +128,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Promise<[Pet]> */ - open class func findPetsByStatus( status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[Pet]> { + open class func findPetsByStatus( status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Promise<[Pet]> { let deferred = Promise<[Pet]>.pending() findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { @@ -151,7 +151,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md index 0d4d1a6ce26..5164a64867d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/FakeAPI.md @@ -416,7 +416,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters( enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Promise + open class func testEnumParameters( enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Promise ``` To test enum parameters diff --git a/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md index 8a516ca3014..41d27fed4e7 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/promisekitLibrary/docs/PetAPI.md @@ -109,7 +109,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus( status: [String]) -> Promise<[Pet]> + open class func findPetsByStatus( status: [Status_findPetsByStatus]) -> Promise<[Pet]> ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 87d1539d825..a5165719f10 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5c22a59a5c5..bd5c091925b 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md b/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md +++ b/samples/client/petstore/swift5/readonlyProperties/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 1bb864f1684..db0c4cb351c 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the result */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index ff5d3c3db10..33bc3ed33a9 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the result */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], ErrorResponse>) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ result: Swift.Result<[Pet], ErrorResponse>) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/resultLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 7836542dbe0..4d998a53217 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -533,7 +533,7 @@ open class FakeAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable */ - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable { return Observable.create { observer -> Disposable in let task = testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { @@ -565,7 +565,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 1f346ba1019..73e4a43c655 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -138,7 +138,7 @@ open class PetAPI { - parameter apiResponseQueue: The queue on which api response is dispatched. - returns: Observable<[Pet]> */ - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[Pet]> { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue) -> Observable<[Pet]> { return Observable.create { observer -> Disposable in let task = findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { @@ -166,7 +166,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md index aecb7880a3c..350928e8e7f 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/FakeAPI.md @@ -366,7 +366,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Observable + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> Observable ``` To test enum parameters diff --git a/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md index a87db33f46d..9f9a42ca4f5 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/rxswiftLibrary/docs/PetAPI.md @@ -95,7 +95,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String]) -> Observable<[Pet]> + open class func findPetsByStatus(status: [Status_findPetsByStatus]) -> Observable<[Pet]> ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift index 016a94b531a..80d050c6d3e 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift @@ -488,7 +488,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -513,7 +513,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift index 2bbb5aba079..ffcf8725e94 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift @@ -129,7 +129,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -150,7 +150,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/urlsessionLibrary/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md b/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md index cc68117f304..2cb0e52af6d 100644 --- a/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/vaporLibrary/docs/FakeAPI.md @@ -575,7 +575,7 @@ public enum TestEndpointParameters { # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, headers: HTTPHeaders = PetstoreClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, headers: HTTPHeaders = PetstoreClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture ``` To test enum parameters diff --git a/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md b/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md index f93e01e6d5d..3fc719012eb 100644 --- a/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md +++ b/samples/client/petstore/swift5/vaporLibrary/docs/PetAPI.md @@ -137,7 +137,7 @@ public enum DeletePet { # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], headers: HTTPHeaders = PetstoreClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture + open class func findPetsByStatus(status: [Status_findPetsByStatus], headers: HTTPHeaders = PetstoreClientAPI.customHeaders, beforeSend: (inout ClientRequest) throws -> () = { _ in }) -> EventLoopFuture ``` Finds Pets by status diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 87d1539d825..a5165719f10 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -485,7 +485,7 @@ open class FakeAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in switch result { case .success: @@ -510,7 +510,7 @@ open class FakeAPI { - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) - returns: RequestBuilder */ - open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { let localVariablePath = "/fake" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableFormParams: [String: Any?] = [ diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 5c22a59a5c5..bd5c091925b 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -126,7 +126,7 @@ open class PetAPI { - parameter completion: completion handler to receive the data and the error objects */ @discardableResult - open class func findPetsByStatus(status: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in switch result { case let .success(response): @@ -147,7 +147,7 @@ open class PetAPI { - parameter status: (query) Status values that need to be considered for filter - returns: RequestBuilder<[Pet]> */ - open class func findPetsByStatusWithRequestBuilder(status: [String]) -> RequestBuilder<[Pet]> { + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { let localVariablePath = "/pet/findByStatus" let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath let localVariableParameters: [String: Any]? = nil diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md index f0799125084..69b1faa2b99 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/FakeAPI.md @@ -440,7 +440,7 @@ Void (empty response body) # **testEnumParameters** ```swift - open class func testEnumParameters(enumHeaderStringArray: [String]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [String]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [String]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) ``` To test enum parameters diff --git a/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md index 5babbd06a3c..7dc73a98900 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md +++ b/samples/client/petstore/swift5/x-swift-hashable/docs/PetAPI.md @@ -115,7 +115,7 @@ Void (empty response body) # **findPetsByStatus** ```swift - open class func findPetsByStatus(status: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) ``` Finds Pets by status From acabbe0e884ee903becf6252e801d8bf517f023e Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 1 Dec 2021 13:54:02 +0800 Subject: [PATCH 41/61] Update launcher script to use 4.x as examples --- README.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 8aca24c1a67..7241d3bf309 100644 --- a/README.md +++ b/README.md @@ -223,21 +223,21 @@ Examples: # Execute latest released openapi-generator-cli openapi-generator-cli version -# Execute version 3.1.0 for the current invocation, regardless of the latest released version -OPENAPI_GENERATOR_VERSION=3.1.0 openapi-generator-cli version +# Execute version 4.1.0 for the current invocation, regardless of the latest released version +OPENAPI_GENERATOR_VERSION=4.1.0 openapi-generator-cli version -# Execute version 3.1.0-SNAPSHOT for the current invocation -OPENAPI_GENERATOR_VERSION=3.1.0-SNAPSHOT openapi-generator-cli version +# Execute version 4.1.0-SNAPSHOT for the current invocation +OPENAPI_GENERATOR_VERSION=4.1.0-SNAPSHOT openapi-generator-cli version -# Execute version 3.0.2 for every invocation in the current shell session -export OPENAPI_GENERATOR_VERSION=3.0.2 -openapi-generator-cli version # is 3.0.2 -openapi-generator-cli version # is also 3.0.2 +# Execute version 4.0.2 for every invocation in the current shell session +export OPENAPI_GENERATOR_VERSION=4.0.2 +openapi-generator-cli version # is 4.0.2 +openapi-generator-cli version # is also 4.0.2 # To "install" a specific version, set the variable in .bashrc/.bash_profile -echo "export OPENAPI_GENERATOR_VERSION=3.0.2" >> ~/.bashrc +echo "export OPENAPI_GENERATOR_VERSION=4.0.2" >> ~/.bashrc source ~/.bashrc -openapi-generator-cli version # is always 3.0.2, unless any of the above overrides are done ad hoc +openapi-generator-cli version # is always 4.0.2, unless any of the above overrides are done ad hoc ``` ### [1.4 - Build Projects](#table-of-contents) From 40609ad67702e0c12337b402a2ea2fa6902ccce0 Mon Sep 17 00:00:00 2001 From: agilob Date: Wed, 1 Dec 2021 06:19:28 +0000 Subject: [PATCH 42/61] Add vscode openapi workspace configuration (#10996) * Add vscode openapi workspace * Config changes for more intellij-like behaviour * Remove recommended plugin editorconfig --- openapi-generator.code-workspace | 78 ++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) create mode 100644 openapi-generator.code-workspace diff --git a/openapi-generator.code-workspace b/openapi-generator.code-workspace new file mode 100644 index 00000000000..94b0864b5d8 --- /dev/null +++ b/openapi-generator.code-workspace @@ -0,0 +1,78 @@ +{ + "folders": [ + { + "name": "openapi-generator", + "path": "." + }, + { + "name": "openapi-generator-cli", + "path": "modules/openapi-generator-cli" + }, + { + "name": "openapi-generator-core", + "path": "modules/openapi-generator-core" + }, + { + "name": "openapi-generator-gradle-plugin", + "path": "modules/openapi-generator-gradle-plugin" + }, + { + "name": "openapi-generator-maven-plugin", + "path": "modules/openapi-generator-maven-plugin" + }, + { + "name": "openapi-generator-online", + "path": "modules/openapi-generator-online" + }, + ], + "settings": { + "editor.formatOnType": true, + "editor.linkedEditing": true, + "editor.tabCompletion": "on", + "editor.tabSize": 4, + "editor.renderWhitespace": "boundary", + "editor.suggest.shareSuggestSelections": true, + "editor.suggestSelection": "first", + "editor.semanticHighlighting.enabled": true, + "explorer.confirmDelete": true, + + "files.autoSave": "onFocusChange", + "files.exclude": { + "**/.classpath": true, + "**/.factorypath": true, + "**/.project": true, + "**/.settings": true + }, + "files.trimFinalNewlines": false, + "files.trimTrailingWhitespace": true, + + "task.saveBeforeRun": "always", + + "java.autobuild.enabled": false, + "java.completion.enabled": true, + "java.completion.guessMethodArguments": true, + "java.completion.maxResults": 5, + "java.format.onType.enabled": true, + + "java.referencesCodeLens.enabled": true, + "java.saveActions.organizeImports": true, + "java.showBuildStatusOnStart.enabled": true, + + "java.dependency.autoRefresh": true, + "java.dependency.refreshDelay": 3000, + "java.format.enabled": true, + + "maven.pomfile.autoUpdateEffectivePOM": true, + }, + "extensions": { + "recommendations": [ + "vscjava.vscode-java-pack", + "attilabuti.mustache-syntax-vscode", + "formulahendry.code-runner", + "visualstudioexptteam.vscodeintellicode", + "42crunch.vscode-openapi", + "mermade.openapi-lint" + + ] + } +} \ No newline at end of file From a745f053bd250af43611a517674341e687bdcd58 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Wed, 1 Dec 2021 14:20:39 +0800 Subject: [PATCH 43/61] skip custom adapter for parent object (#10998) --- .../okhttp-gson-nextgen/JSON.mustache | 16 +----- .../okhttp-gson-nextgen/pojo.mustache | 2 + .../java/org/openapitools/client/JSON.java | 2 - .../org/openapitools/client/model/Animal.java | 56 ------------------- .../client/model/GrandparentAnimal.java | 55 ------------------ 5 files changed, 4 insertions(+), 127 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache index 91a7905d0bc..56477b8dc17 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/JSON.mustache @@ -132,21 +132,9 @@ public class JSON { {{#models}} {{#model}} {{^isEnum}} - {{#oneOf}} - {{#-first}} + {{^hasChildren}} .registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()) - {{/-first}} - {{/oneOf}} - {{^oneOf}} - {{#anyOf}} - {{#-first}} - .registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()) - {{/-first}} - {{/anyOf}} - {{^anyOf}} - .registerTypeAdapterFactory(new {{modelPackage}}.{{{classname}}}.CustomTypeAdapterFactory()) - {{/anyOf}} - {{/oneOf}} + {{/hasChildren}} {{/isEnum}} {{/model}} {{/models}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache index df9dbc320d4..f7ad1e3a05a 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson-nextgen/pojo.mustache @@ -379,6 +379,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens } }; {{/parcelableModel}} +{{^hasChildren}} public static HashSet openapiFields; public static HashSet openapiRequiredFields; @@ -442,4 +443,5 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens }.nullSafe(); } } +{{/hasChildren}} } \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java index 53717e8ac51..40146a3e6f5 100644 --- a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/JSON.java @@ -221,7 +221,6 @@ public class JSON { .registerTypeAdapter(LocalDate.class, localDateTypeAdapter) .registerTypeAdapter(byte[].class, byteArrayAdapter) .registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesClass.CustomTypeAdapterFactory()) - .registerTypeAdapterFactory(new org.openapitools.client.model.Animal.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.Apple.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.AppleReq.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.ArrayOfArrayOfNumberOnly.CustomTypeAdapterFactory()) @@ -251,7 +250,6 @@ public class JSON { .registerTypeAdapterFactory(new org.openapitools.client.model.Fruit.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.FruitReq.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.GmFruit.CustomTypeAdapterFactory()) - .registerTypeAdapterFactory(new org.openapitools.client.model.GrandparentAnimal.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.HasOnlyReadOnly.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.HealthCheckResult.CustomTypeAdapterFactory()) .registerTypeAdapterFactory(new org.openapitools.client.model.InlineResponseDefault.CustomTypeAdapterFactory()) diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java index cf1f00de64f..4d60101ca17 100644 --- a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/Animal.java @@ -144,60 +144,4 @@ public class Animal { return o.toString().replace("\n", "\n "); } - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("className"); - openapiFields.add("color"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("className"); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!Animal.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'Animal' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(Animal.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, Animal value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public Animal read(JsonReader in) throws IOException { - JsonObject obj = elementAdapter.read(in).getAsJsonObject(); - Set> entries = obj.entrySet();//will return members of your object - // check to see if the JSON string contains additional fields - for (Entry entry: entries) { - if (!Animal.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `Animal` properties"); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : Animal.openapiRequiredFields) { - if (obj.get(requiredField) == null) { - throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); - } - } - - return thisAdapter.fromJsonTree(obj); - } - - }.nullSafe(); - } - } } diff --git a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java index df924fe5f33..085ccbfbfc1 100644 --- a/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java +++ b/samples/client/petstore/java/okhttp-gson-nextgen/src/main/java/org/openapitools/client/model/GrandparentAnimal.java @@ -114,59 +114,4 @@ public class GrandparentAnimal { return o.toString().replace("\n", "\n "); } - public static HashSet openapiFields; - public static HashSet openapiRequiredFields; - - static { - // a set of all properties/fields (JSON key names) - openapiFields = new HashSet(); - openapiFields.add("pet_type"); - - // a set of required properties/fields (JSON key names) - openapiRequiredFields = new HashSet(); - openapiRequiredFields.add("pet_type"); - } - - public static class CustomTypeAdapterFactory implements TypeAdapterFactory { - @SuppressWarnings("unchecked") - @Override - public TypeAdapter create(Gson gson, TypeToken type) { - if (!GrandparentAnimal.class.isAssignableFrom(type.getRawType())) { - return null; // this class only serializes 'GrandparentAnimal' and its subtypes - } - final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); - final TypeAdapter thisAdapter - = gson.getDelegateAdapter(this, TypeToken.get(GrandparentAnimal.class)); - - return (TypeAdapter) new TypeAdapter() { - @Override - public void write(JsonWriter out, GrandparentAnimal value) throws IOException { - JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); - elementAdapter.write(out, obj); - } - - @Override - public GrandparentAnimal read(JsonReader in) throws IOException { - JsonObject obj = elementAdapter.read(in).getAsJsonObject(); - Set> entries = obj.entrySet();//will return members of your object - // check to see if the JSON string contains additional fields - for (Entry entry: entries) { - if (!GrandparentAnimal.openapiFields.contains(entry.getKey())) { - throw new IllegalArgumentException("The field `" + entry.getKey() + "` in the JSON string is not defined in the `GrandparentAnimal` properties"); - } - } - - // check to make sure all required properties/fields are present in the JSON string - for (String requiredField : GrandparentAnimal.openapiRequiredFields) { - if (obj.get(requiredField) == null) { - throw new IllegalArgumentException("The required field `" + requiredField + "` is not found in the JSON string"); - } - } - - return thisAdapter.fromJsonTree(obj); - } - - }.nullSafe(); - } - } } From 56e7f811bc634eea50576e3445180eb8d2e6f598 Mon Sep 17 00:00:00 2001 From: Deniz Dogan Date: Wed, 1 Dec 2021 07:49:00 +0100 Subject: [PATCH 44/61] Add Hashable to oneOf enums (#10971) Fixes #10970 --- .../src/main/resources/swift5/modelOneOf.mustache | 2 +- .../oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache index fae34faa975..1c16a3955bc 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelOneOf.mustache @@ -1,4 +1,4 @@ -public enum {{classname}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{/useVapor}} { +public enum {{classname}}: {{#useVapor}}Content{{/useVapor}}{{^useVapor}}Codable{{#vendorExtensions.x-swift-hashable}}, Hashable{{/vendorExtensions.x-swift-hashable}}{{/useVapor}} { {{#oneOf}} case type{{.}}({{.}}) {{/oneOf}} diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift index d58ad1f8b31..c249774d2a2 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models/Fruit.swift @@ -10,7 +10,7 @@ import Foundation import AnyCodable #endif -public enum Fruit: Codable { +public enum Fruit: Codable, Hashable { case typeApple(Apple) case typeBanana(Banana) From ef31941b1314d1d60f6aed5d29a72a278052748f Mon Sep 17 00:00:00 2001 From: jiangyuan <469391363@qq.com> Date: Fri, 3 Dec 2021 00:50:52 +0800 Subject: [PATCH 45/61] fix file path (#11005) Co-authored-by: jiangyuan04 --- .../codegen/languages/PythonLegacyClientCodegen.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java index 138b1c54356..05b5b92df39 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonLegacyClientCodegen.java @@ -215,6 +215,9 @@ public class PythonLegacyClientCodegen extends AbstractPythonCodegen implements } } + String modelPath = packagePath() + File.separatorChar + modelPackage.replace('.', File.separatorChar); + String apiPath = packagePath() + File.separatorChar + apiPackage.replace('.', File.separatorChar); + String readmePath = "README.md"; String readmeTemplate = "README.mustache"; if (generateSourceCodeOnly) { @@ -237,8 +240,8 @@ public class PythonLegacyClientCodegen extends AbstractPythonCodegen implements } supportingFiles.add(new SupportingFile("configuration.mustache", packagePath(), "configuration.py")); supportingFiles.add(new SupportingFile("__init__package.mustache", packagePath(), "__init__.py")); - supportingFiles.add(new SupportingFile("__init__model.mustache", packagePath() + File.separatorChar + modelPackage, "__init__.py")); - supportingFiles.add(new SupportingFile("__init__api.mustache", packagePath() + File.separatorChar + apiPackage, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__model.mustache", modelPath, "__init__.py")); + supportingFiles.add(new SupportingFile("__init__api.mustache", apiPath, "__init__.py")); // If the package name consists of dots(openapi.client), then we need to create the directory structure like openapi/client with __init__ files. String[] packageNameSplits = packageName.split("\\."); From b915ad99a8068330ea90bbffbc7ba9a7dcd2855e Mon Sep 17 00:00:00 2001 From: cghislai Date: Fri, 3 Dec 2021 09:10:40 +0100 Subject: [PATCH 46/61] typescript-angular: Add supports for v13 (#10877) --- ...angular-v13-provided-in-root-with-npm.yaml | 11 + ...pescript-angular-v13-provided-in-root.yaml | 7 + docs/generators/typescript-angular.md | 2 +- .../TypeScriptAngularClientCodegen.java | 19 +- .../builds/default/.gitignore | 4 + .../builds/default/.openapi-generator-ignore | 23 + .../builds/default/.openapi-generator/FILES | 19 + .../builds/default/.openapi-generator/VERSION | 1 + .../builds/default/README.md | 203 ++++++ .../builds/default/api.module.ts | 33 + .../builds/default/api/api.ts | 7 + .../builds/default/api/pet.service.ts | 666 ++++++++++++++++++ .../builds/default/api/store.service.ts | 311 ++++++++ .../builds/default/api/user.service.ts | 549 +++++++++++++++ .../builds/default/configuration.ts | 141 ++++ .../builds/default/encoder.ts | 20 + .../builds/default/git_push.sh | 57 ++ .../builds/default/index.ts | 5 + .../builds/default/model/apiResponse.ts | 22 + .../builds/default/model/category.ts | 21 + .../builds/default/model/models.ts | 6 + .../builds/default/model/order.ts | 37 + .../builds/default/model/pet.ts | 39 + .../builds/default/model/tag.ts | 21 + .../builds/default/model/user.ts | 30 + .../builds/default/variables.ts | 9 + .../builds/with-npm/.gitignore | 4 + .../builds/with-npm/.openapi-generator-ignore | 23 + .../builds/with-npm/.openapi-generator/FILES | 22 + .../with-npm/.openapi-generator/VERSION | 1 + .../builds/with-npm/README.md | 203 ++++++ .../builds/with-npm/api.module.ts | 33 + .../builds/with-npm/api/api.ts | 7 + .../builds/with-npm/api/pet.service.ts | 666 ++++++++++++++++++ .../builds/with-npm/api/store.service.ts | 311 ++++++++ .../builds/with-npm/api/user.service.ts | 549 +++++++++++++++ .../builds/with-npm/configuration.ts | 141 ++++ .../builds/with-npm/encoder.ts | 20 + .../builds/with-npm/git_push.sh | 57 ++ .../builds/with-npm/index.ts | 5 + .../builds/with-npm/model/apiResponse.ts | 22 + .../builds/with-npm/model/category.ts | 21 + .../builds/with-npm/model/models.ts | 6 + .../builds/with-npm/model/order.ts | 37 + .../builds/with-npm/model/pet.ts | 39 + .../builds/with-npm/model/tag.ts | 21 + .../builds/with-npm/model/user.ts | 30 + .../builds/with-npm/ng-package.json | 6 + .../builds/with-npm/package.json | 34 + .../builds/with-npm/tsconfig.json | 28 + .../builds/with-npm/variables.ts | 9 + 51 files changed, 4551 insertions(+), 7 deletions(-) create mode 100644 bin/configs/typescript-angular-v13-provided-in-root-with-npm.yaml create mode 100644 bin/configs/typescript-angular-v13-provided-in-root.yaml create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.gitignore create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator-ignore create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api.module.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/api.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/encoder.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/git_push.sh create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/apiResponse.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/category.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/models.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/order.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/pet.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/tag.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/user.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/variables.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.gitignore create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator-ignore create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api.module.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/api.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/encoder.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/git_push.sh create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/apiResponse.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/category.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/models.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/order.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/pet.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/tag.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/user.ts create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/ng-package.json create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/package.json create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/tsconfig.json create mode 100644 samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/variables.ts diff --git a/bin/configs/typescript-angular-v13-provided-in-root-with-npm.yaml b/bin/configs/typescript-angular-v13-provided-in-root-with-npm.yaml new file mode 100644 index 00000000000..22284f92f6c --- /dev/null +++ b/bin/configs/typescript-angular-v13-provided-in-root-with-npm.yaml @@ -0,0 +1,11 @@ +generatorName: typescript-angular +outputDir: samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-angular +additionalProperties: + ngVersion: 13.0.1 + npmVersion: 1.0.0 + npmName: '@openapitools/typescript-angular-petstore' + npmRepository: https://skimdb.npmjs.com/registry + snapshot: false + supportsES6: true diff --git a/bin/configs/typescript-angular-v13-provided-in-root.yaml b/bin/configs/typescript-angular-v13-provided-in-root.yaml new file mode 100644 index 00000000000..bf16e022ded --- /dev/null +++ b/bin/configs/typescript-angular-v13-provided-in-root.yaml @@ -0,0 +1,7 @@ +generatorName: typescript-angular +outputDir: samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-angular +additionalProperties: + ngVersion: 13.0.1 + supportsES6: true diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index ab8b3da35fc..2083b09cadf 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -19,7 +19,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |modelFileSuffix|The suffix of the file of the generated model (model<suffix>.ts).| |null| |modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name. Only change it if you provide your own run-time code for (de-)serialization of models| |original| |modelSuffix|The suffix of the generated model.| |null| -|ngVersion|The version of Angular. (At least 6.0.0)| |12.2.12| +|ngVersion|The version of Angular. (At least 6.0.0)| |13.0.1| |npmName|The name under which you want to publish generated npm package. Required to generate a full package| |null| |npmRepository|Use this property to set an url your private npmRepo in the package.json| |null| |npmVersion|The version of your npm package. If not provided, using the version from the OpenAPI specification file.| |1.0.0| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java index 758f2650f5a..858e33d0c53 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java @@ -67,7 +67,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode public static final String STRING_ENUMS_DESC = "Generate string enums instead of objects for enum values."; public static final String QUERY_PARAM_OBJECT_FORMAT = "queryParamObjectFormat"; - protected String ngVersion = "12.2.12"; + protected String ngVersion = "13.0.1"; protected String npmRepository = null; private boolean useSingleRequestParameter = false; protected String serviceSuffix = "Service"; @@ -146,7 +146,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode @Override public String getHelp() { - return "Generates a TypeScript Angular (6.x - 12.x) client library."; + return "Generates a TypeScript Angular (6.x - 13.x) client library."; } @Override @@ -243,7 +243,7 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } else { additionalProperties.put(DELETE_ACCEPTS_BODY, false); } - + additionalProperties.put(NG_VERSION, ngVersion); if (additionalProperties.containsKey(API_MODULE_PREFIX)) { @@ -300,7 +300,9 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } // Set the typescript version compatible to the Angular version - if (ngVersion.atLeast("12.0.0")) { + if (ngVersion.atLeast("13.0.0")) { + additionalProperties.put("tsVersion", ">=4.4.2 <4.5.0"); + } else if (ngVersion.atLeast("12.0.0")) { additionalProperties.put("tsVersion", ">=4.3.0 <4.4.0"); } else if (ngVersion.atLeast("11.0.0")) { additionalProperties.put("tsVersion", ">=4.0.0 <4.1.0"); @@ -318,7 +320,9 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode } // Set the rxJS version compatible to the Angular version - if (ngVersion.atLeast("10.0.0")) { + if (ngVersion.atLeast("13.0.0")) { + additionalProperties.put("rxjsVersion", "7.4.0"); + } else if (ngVersion.atLeast("10.0.0")) { additionalProperties.put("rxjsVersion", "6.6.0"); } else if (ngVersion.atLeast("9.0.0")) { additionalProperties.put("rxjsVersion", "6.5.3"); @@ -334,7 +338,10 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode supportingFiles.add(new SupportingFile("ng-package.mustache", getIndexDirectory(), "ng-package.json")); // Specific ng-packagr configuration - if (ngVersion.atLeast("12.0.0")) { + if (ngVersion.atLeast("13.0.0")) { + additionalProperties.put("ngPackagrVersion", "13.0.3"); + additionalProperties.put("tsickleVersion", "0.43.0"); + } else if (ngVersion.atLeast("12.0.0")) { additionalProperties.put("ngPackagrVersion", "12.2.1"); additionalProperties.put("tsickleVersion", "0.43.0"); } else if (ngVersion.atLeast("11.0.0")) { diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.gitignore b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.gitignore new file mode 100644 index 00000000000..149b5765472 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator-ignore b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES new file mode 100644 index 00000000000..7f8ebffb302 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/FILES @@ -0,0 +1,19 @@ +.gitignore +README.md +api.module.ts +api/api.ts +api/pet.service.ts +api/store.service.ts +api/user.service.ts +configuration.ts +encoder.ts +git_push.sh +index.ts +model/apiResponse.ts +model/category.ts +model/models.ts +model/order.ts +model/pet.ts +model/tag.ts +model/user.ts +variables.ts diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION new file mode 100644 index 00000000000..4077803655c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md new file mode 100644 index 00000000000..f2e5a1c1ee2 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/README.md @@ -0,0 +1,203 @@ +## @ + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @ --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from ''; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from ''; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from ''; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from ''; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from ''; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from ''; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from ''; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api.module.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api.module.ts new file mode 100644 index 00000000000..2afb8f64e92 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api.module.ts @@ -0,0 +1,33 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/api.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/api.ts new file mode 100644 index 00000000000..8e44b64083d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts new file mode 100644 index 00000000000..4e6194e7b10 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/pet.service.ts @@ -0,0 +1,666 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { ApiResponse } from '../model/apiResponse'; +// @ts-ignore +import { Pet } from '../model/pet'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class PetService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Add a new pet to the store + * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Deletes a pet + * @param petId Pet id to delete + * @param apiKey + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + let localVarHeaders = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + localVarHeaders = localVarHeaders.set('api_key', String(apiKey)); + } + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (status) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + status.join(COLLECTION_FORMATS['csv']), 'status'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + * @deprecated + */ + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (tags) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + tags.join(COLLECTION_FORMATS['csv']), 'tags'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Update an existing pet + * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/pet`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updates a pet in the store with form data + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (name !== undefined) { + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; + } + if (status !== undefined) { + localVarFormParams = localVarFormParams.append('status', status) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * uploads an image + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (additionalMetadata !== undefined) { + localVarFormParams = localVarFormParams.append('additionalMetadata', additionalMetadata) as any || localVarFormParams; + } + if (file !== undefined) { + localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts new file mode 100644 index 00000000000..9d00e8b652c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/store.service.ts @@ -0,0 +1,311 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { Order } from '../model/order'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class StoreService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Place an order for a pet + * @param body order placed for purchasing the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/store/order`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts new file mode 100644 index 00000000000..7fc46dada8a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/api/user.service.ts @@ -0,0 +1,549 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { User } from '../model/user'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class UserService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Get user by user name + * @param username The name that needs to be fetched. Use user1 for testing. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs user into the system + * @param username The user name for login + * @param password The password for login in clear text + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (username !== undefined && username !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + username, 'username'); + } + if (password !== undefined && password !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + password, 'password'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/login`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs out current logged in user session + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts new file mode 100644 index 00000000000..6fc0f80d973 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/configuration.ts @@ -0,0 +1,141 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + + // init default api_key credential + if (!this.credentials['api_key']) { + this.credentials['api_key'] = () => { + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } + }; + } + + // init default petstore_auth credential + if (!this.credentials['petstore_auth']) { + this.credentials['petstore_auth'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/encoder.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/encoder.ts new file mode 100644 index 00000000000..138c4d5cf2c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/git_push.sh b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/git_push.sh new file mode 100644 index 00000000000..f53a75d4fab --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/git_push.sh @@ -0,0 +1,57 @@ +#!/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-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts new file mode 100644 index 00000000000..c312b70fa3e --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/index.ts @@ -0,0 +1,5 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/apiResponse.ts new file mode 100644 index 00000000000..682ba478921 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/apiResponse.ts @@ -0,0 +1,22 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/category.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/category.ts new file mode 100644 index 00000000000..b988b6827a0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/category.ts @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/models.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/models.ts new file mode 100644 index 00000000000..8607c5dabd0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/order.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/order.ts new file mode 100644 index 00000000000..a29bebe4906 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/order.ts @@ -0,0 +1,37 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: string; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/pet.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/pet.ts new file mode 100644 index 00000000000..e0404395f91 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/pet.ts @@ -0,0 +1,39 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/tag.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/tag.ts new file mode 100644 index 00000000000..b6ff210e8df --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/tag.ts @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/user.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/user.ts new file mode 100644 index 00000000000..fce51005300 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/model/user.ts @@ -0,0 +1,30 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/variables.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/variables.ts new file mode 100644 index 00000000000..6fe58549f39 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.gitignore b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.gitignore new file mode 100644 index 00000000000..149b5765472 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator-ignore b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES new file mode 100644 index 00000000000..5db7bd76369 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/FILES @@ -0,0 +1,22 @@ +.gitignore +README.md +api.module.ts +api/api.ts +api/pet.service.ts +api/store.service.ts +api/user.service.ts +configuration.ts +encoder.ts +git_push.sh +index.ts +model/apiResponse.ts +model/category.ts +model/models.ts +model/order.ts +model/pet.ts +model/tag.ts +model/user.ts +ng-package.json +package.json +tsconfig.json +variables.ts diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION new file mode 100644 index 00000000000..4077803655c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md new file mode 100644 index 00000000000..000c51d694b --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/README.md @@ -0,0 +1,203 @@ +## @openapitools/typescript-angular-petstore@1.0.0 + +### Building + +To install the required dependencies and to build the typescript sources run: +``` +npm install +npm run build +``` + +### publishing + +First build the package then run ```npm publish dist``` (don't forget to specify the `dist` folder!) + +### consuming + +Navigate to the folder of your consuming project and run one of next commands. + +_published:_ + +``` +npm install @openapitools/typescript-angular-petstore@1.0.0 --save +``` + +_without publishing (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE/dist.tgz --save +``` + +_It's important to take the tgz file, otherwise you'll get trouble with links on windows_ + +_using `npm link`:_ + +In PATH_TO_GENERATED_PACKAGE/dist: +``` +npm link +``` + +In your project: +``` +npm link @openapitools/typescript-angular-petstore +``` + +__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. +Please refer to this issue https://github.com/angular/angular-cli/issues/8284 for a solution / workaround. +Published packages are not effected by this issue. + + +#### General usage + +In your Angular project: + + +``` +// without configuring providers +import { ApiModule } from '@openapitools/typescript-angular-petstore'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers +import { ApiModule, Configuration, ConfigurationParameters } from '@openapitools/typescript-angular-petstore'; + +export function apiConfigFactory (): Configuration { + const params: ConfigurationParameters = { + // set configuration parameters here. + } + return new Configuration(params); +} + +@NgModule({ + imports: [ ApiModule.forRoot(apiConfigFactory) ], + declarations: [ AppComponent ], + providers: [], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +// configuring providers with an authentication service that manages your access tokens +import { ApiModule, Configuration } from '@openapitools/typescript-angular-petstore'; + +@NgModule({ + imports: [ ApiModule ], + declarations: [ AppComponent ], + providers: [ + { + provide: Configuration, + useFactory: (authService: AuthService) => new Configuration( + { + basePath: environment.apiUrl, + accessToken: authService.getAccessToken.bind(authService) + } + ), + deps: [AuthService], + multi: false + } + ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + +``` +import { DefaultApi } from '@openapitools/typescript-angular-petstore'; + +export class AppComponent { + constructor(private apiGateway: DefaultApi) { } +} +``` + +Note: The ApiModule is restricted to being instantiated once app wide. +This is to ensure that all services are treated as singletons. + +#### Using multiple OpenAPI files / APIs / ApiModules +In order to use multiple `ApiModules` generated from different OpenAPI files, +you can create an alias name when importing the modules +in order to avoid naming conflicts: +``` +import { ApiModule } from 'my-api-path'; +import { ApiModule as OtherApiModule } from 'my-other-api-path'; +import { HttpClientModule } from '@angular/common/http'; + +@NgModule({ + imports: [ + ApiModule, + OtherApiModule, + // make sure to import the HttpClientModule in the AppModule only, + // see https://github.com/angular/angular/issues/20575 + HttpClientModule + ] +}) +export class AppModule { + +} +``` + + +### Set service base path +If different than the generated base path, during app bootstrap, you can provide the base path to your service. + +``` +import { BASE_PATH } from '@openapitools/typescript-angular-petstore'; + +bootstrap(AppComponent, [ + { provide: BASE_PATH, useValue: 'https://your-web-service.com' }, +]); +``` +or + +``` +import { BASE_PATH } from '@openapitools/typescript-angular-petstore'; + +@NgModule({ + imports: [], + declarations: [ AppComponent ], + providers: [ provide: BASE_PATH, useValue: 'https://your-web-service.com' ], + bootstrap: [ AppComponent ] +}) +export class AppModule {} +``` + + +#### Using @angular/cli +First extend your `src/environments/*.ts` files by adding the corresponding base path: + +``` +export const environment = { + production: false, + API_BASE_PATH: 'http://127.0.0.1:8080' +}; +``` + +In the src/app/app.module.ts: +``` +import { BASE_PATH } from '@openapitools/typescript-angular-petstore'; +import { environment } from '../environments/environment'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ ], + providers: [{ provide: BASE_PATH, useValue: environment.API_BASE_PATH }], + bootstrap: [ AppComponent ] +}) +export class AppModule { } +``` diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api.module.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api.module.ts new file mode 100644 index 00000000000..2afb8f64e92 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api.module.ts @@ -0,0 +1,33 @@ +import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; +import { Configuration } from './configuration'; +import { HttpClient } from '@angular/common/http'; + +import { PetService } from './api/pet.service'; +import { StoreService } from './api/store.service'; +import { UserService } from './api/user.service'; + +@NgModule({ + imports: [], + declarations: [], + exports: [], + providers: [] +}) +export class ApiModule { + public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders { + return { + ngModule: ApiModule, + providers: [ { provide: Configuration, useFactory: configurationFactory } ] + }; + } + + constructor( @Optional() @SkipSelf() parentModule: ApiModule, + @Optional() http: HttpClient) { + if (parentModule) { + throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); + } + if (!http) { + throw new Error('You need to import the HttpClientModule in your AppModule! \n' + + 'See also https://github.com/angular/angular/issues/20575'); + } + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/api.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/api.ts new file mode 100644 index 00000000000..8e44b64083d --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/api.ts @@ -0,0 +1,7 @@ +export * from './pet.service'; +import { PetService } from './pet.service'; +export * from './store.service'; +import { StoreService } from './store.service'; +export * from './user.service'; +import { UserService } from './user.service'; +export const APIS = [PetService, StoreService, UserService]; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts new file mode 100644 index 00000000000..4e6194e7b10 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/pet.service.ts @@ -0,0 +1,666 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { ApiResponse } from '../model/apiResponse'; +// @ts-ignore +import { Pet } from '../model/pet'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class PetService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + /** + * @param consumes string[] mime-types + * @return true: consumes contains 'multipart/form-data', false: otherwise + */ + private canConsumeForm(consumes: string[]): boolean { + const form = 'multipart/form-data'; + for (const consume of consumes) { + if (form === consume) { + return true; + } + } + return false; + } + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Add a new pet to the store + * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public addPet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public addPet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public addPet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling addPet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Deletes a pet + * @param petId Pet id to delete + * @param apiKey + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deletePet(petId: number, apiKey?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deletePet(petId: number, apiKey?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deletePet(petId: number, apiKey?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling deletePet.'); + } + + let localVarHeaders = this.defaultHeaders; + if (apiKey !== undefined && apiKey !== null) { + localVarHeaders = localVarHeaders.set('api_key', String(apiKey)); + } + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByStatus(status: Array<'available' | 'pending' | 'sold'>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (status === null || status === undefined) { + throw new Error('Required parameter status was null or undefined when calling findPetsByStatus.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (status) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + status.join(COLLECTION_FORMATS['csv']), 'status'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByStatus`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + * @deprecated + */ + public findPetsByTags(tags: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public findPetsByTags(tags: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>>; + public findPetsByTags(tags: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (tags === null || tags === undefined) { + throw new Error('Required parameter tags was null or undefined when calling findPetsByTags.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (tags) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + tags.join(COLLECTION_FORMATS['csv']), 'tags'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get>(`${this.configuration.basePath}/pet/findByTags`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getPetById(petId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getPetById(petId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getPetById(petId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling getPetById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Update an existing pet + * @param body Pet object that needs to be added to the store + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePet(body: Pet, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePet(body: Pet, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePet(body: Pet, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updatePet.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/json', + 'application/xml' + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/pet`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updates a pet in the store with form data + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updatePetWithForm(petId: number, name?: string, status?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling updatePetWithForm.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'application/x-www-form-urlencoded' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (name !== undefined) { + localVarFormParams = localVarFormParams.append('name', name) as any || localVarFormParams; + } + if (status !== undefined) { + localVarFormParams = localVarFormParams.append('status', status) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * uploads an image + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public uploadFile(petId: number, additionalMetadata?: string, file?: Blob, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + if (petId === null || petId === undefined) { + throw new Error('Required parameter petId was null or undefined when calling uploadFile.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (petstore_auth) required + localVarCredential = this.configuration.lookupCredential('petstore_auth'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('Authorization', 'Bearer ' + localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + // to determine the Content-Type header + const consumes: string[] = [ + 'multipart/form-data' + ]; + + const canConsumeForm = this.canConsumeForm(consumes); + + let localVarFormParams: { append(param: string, value: any): any; }; + let localVarUseForm = false; + let localVarConvertFormParamsToString = false; + // use FormData to transmit files using content-type "multipart/form-data" + // see https://stackoverflow.com/questions/4007969/application-x-www-form-urlencoded-or-multipart-form-data + localVarUseForm = canConsumeForm; + if (localVarUseForm) { + localVarFormParams = new FormData(); + } else { + localVarFormParams = new HttpParams({encoder: this.encoder}); + } + + if (additionalMetadata !== undefined) { + localVarFormParams = localVarFormParams.append('additionalMetadata', additionalMetadata) as any || localVarFormParams; + } + if (file !== undefined) { + localVarFormParams = localVarFormParams.append('file', file) as any || localVarFormParams; + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/pet/${encodeURIComponent(String(petId))}/uploadImage`, + localVarConvertFormParamsToString ? localVarFormParams.toString() : localVarFormParams, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts new file mode 100644 index 00000000000..9d00e8b652c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/store.service.ts @@ -0,0 +1,311 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { Order } from '../model/order'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class StoreService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteOrder(orderId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteOrder(orderId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteOrder(orderId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling deleteOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getInventory(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable<{ [key: string]: number; }>; + public getInventory(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable>; + public getInventory(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarCredential: string | undefined; + // authentication (api_key) required + localVarCredential = this.configuration.lookupCredential('api_key'); + if (localVarCredential) { + localVarHeaders = localVarHeaders.set('api_key', localVarCredential); + } + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get<{ [key: string]: number; }>(`${this.configuration.basePath}/store/inventory`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * 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 + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getOrderById(orderId: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getOrderById(orderId: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getOrderById(orderId: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (orderId === null || orderId === undefined) { + throw new Error('Required parameter orderId was null or undefined when calling getOrderById.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/store/order/${encodeURIComponent(String(orderId))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Place an order for a pet + * @param body order placed for purchasing the pet + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public placeOrder(body: Order, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public placeOrder(body: Order, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public placeOrder(body: Order, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling placeOrder.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/store/order`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts new file mode 100644 index 00000000000..7fc46dada8a --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/api/user.service.ts @@ -0,0 +1,549 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ +/* tslint:disable:no-unused-variable member-ordering */ + +import { Inject, Injectable, Optional } from '@angular/core'; +import { HttpClient, HttpHeaders, HttpParams, + HttpResponse, HttpEvent, HttpParameterCodec, HttpContext + } from '@angular/common/http'; +import { CustomHttpParameterCodec } from '../encoder'; +import { Observable } from 'rxjs'; + +// @ts-ignore +import { User } from '../model/user'; + +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; +import { Configuration } from '../configuration'; + + + +@Injectable({ + providedIn: 'root' +}) +export class UserService { + + protected basePath = 'http://petstore.swagger.io/v2'; + public defaultHeaders = new HttpHeaders(); + public configuration = new Configuration(); + public encoder: HttpParameterCodec; + + constructor(protected httpClient: HttpClient, @Optional()@Inject(BASE_PATH) basePath: string, @Optional() configuration: Configuration) { + if (configuration) { + this.configuration = configuration; + } + if (typeof this.configuration.basePath !== 'string') { + if (typeof basePath !== 'string') { + basePath = this.basePath; + } + this.configuration.basePath = basePath; + } + this.encoder = this.configuration.encoder || new CustomHttpParameterCodec(); + } + + + private addToHttpParams(httpParams: HttpParams, value: any, key?: string): HttpParams { + if (typeof value === "object" && value instanceof Date === false) { + httpParams = this.addToHttpParamsRecursive(httpParams, value); + } else { + httpParams = this.addToHttpParamsRecursive(httpParams, value, key); + } + return httpParams; + } + + private addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string): HttpParams { + if (value == null) { + return httpParams; + } + + if (typeof value === "object") { + if (Array.isArray(value)) { + (value as any[]).forEach( elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)); + } else if (value instanceof Date) { + if (key != null) { + httpParams = httpParams.append(key, + (value as Date).toISOString().substr(0, 10)); + } else { + throw Error("key may not be null if value is Date"); + } + } else { + Object.keys(value).forEach( k => httpParams = this.addToHttpParamsRecursive( + httpParams, value[k], key != null ? `${key}.${k}` : k)); + } + } else if (key != null) { + httpParams = httpParams.append(key, value); + } else { + throw Error("key may not be null if value is not object or array"); + } + return httpParams; + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUser(body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUser(body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUser(body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithArrayInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithArrayInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithArrayInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithArrayInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithArray`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Creates list of users with given input array + * @param body List of user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public createUsersWithListInput(body: Array, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public createUsersWithListInput(body: Array, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public createUsersWithListInput(body: Array, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling createUsersWithListInput.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.post(`${this.configuration.basePath}/user/createWithList`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public deleteUser(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public deleteUser(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public deleteUser(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling deleteUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.delete(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + null, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Get user by user name + * @param username The name that needs to be fetched. Use user1 for testing. + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public getUserByName(username: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public getUserByName(username: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public getUserByName(username: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling getUserByName.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs user into the system + * @param username The user name for login + * @param password The password for login in clear text + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public loginUser(username: string, password: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable; + public loginUser(username: string, password: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable>; + public loginUser(username: string, password: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/xml' | 'application/json', context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling loginUser.'); + } + if (password === null || password === undefined) { + throw new Error('Required parameter password was null or undefined when calling loginUser.'); + } + + let localVarQueryParameters = new HttpParams({encoder: this.encoder}); + if (username !== undefined && username !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + username, 'username'); + } + if (password !== undefined && password !== null) { + localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, + password, 'password'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + 'application/xml', + 'application/json' + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/login`, + { + context: localVarHttpContext, + params: localVarQueryParameters, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Logs out current logged in user session + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public logoutUser(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public logoutUser(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public logoutUser(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.get(`${this.configuration.basePath}/user/logout`, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. + * @param reportProgress flag to report request and response progress. + */ + public updateUser(username: string, body: User, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable; + public updateUser(username: string, body: User, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable>; + public updateUser(username: string, body: User, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: undefined, context?: HttpContext}): Observable { + if (username === null || username === undefined) { + throw new Error('Required parameter username was null or undefined when calling updateUser.'); + } + if (body === null || body === undefined) { + throw new Error('Required parameter body was null or undefined when calling updateUser.'); + } + + let localVarHeaders = this.defaultHeaders; + + let localVarHttpHeaderAcceptSelected: string | undefined = options && options.httpHeaderAccept; + if (localVarHttpHeaderAcceptSelected === undefined) { + // to determine the Accept header + const httpHeaderAccepts: string[] = [ + ]; + localVarHttpHeaderAcceptSelected = this.configuration.selectHeaderAccept(httpHeaderAccepts); + } + if (localVarHttpHeaderAcceptSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); + } + + let localVarHttpContext: HttpContext | undefined = options && options.context; + if (localVarHttpContext === undefined) { + localVarHttpContext = new HttpContext(); + } + + + // to determine the Content-Type header + const consumes: string[] = [ + ]; + const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); + if (httpContentTypeSelected !== undefined) { + localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); + } + + let responseType_: 'text' | 'json' = 'json'; + if(localVarHttpHeaderAcceptSelected && localVarHttpHeaderAcceptSelected.startsWith('text')) { + responseType_ = 'text'; + } + + return this.httpClient.put(`${this.configuration.basePath}/user/${encodeURIComponent(String(username))}`, + body, + { + context: localVarHttpContext, + responseType: responseType_, + withCredentials: this.configuration.withCredentials, + headers: localVarHeaders, + observe: observe, + reportProgress: reportProgress + } + ); + } + +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts new file mode 100644 index 00000000000..6fc0f80d973 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/configuration.ts @@ -0,0 +1,141 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +export interface ConfigurationParameters { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials?: {[ key: string ]: string | (() => string | undefined)}; +} + +export class Configuration { + /** + * @deprecated Since 5.0. Use credentials instead + */ + apiKeys?: {[ key: string ]: string}; + username?: string; + password?: string; + /** + * @deprecated Since 5.0. Use credentials instead + */ + accessToken?: string | (() => string); + basePath?: string; + withCredentials?: boolean; + encoder?: HttpParameterCodec; + /** + * The keys are the names in the securitySchemes section of the OpenAPI + * document. They should map to the value used for authentication + * minus any standard prefixes such as 'Basic' or 'Bearer'. + */ + credentials: {[ key: string ]: string | (() => string | undefined)}; + + constructor(configurationParameters: ConfigurationParameters = {}) { + this.apiKeys = configurationParameters.apiKeys; + this.username = configurationParameters.username; + this.password = configurationParameters.password; + this.accessToken = configurationParameters.accessToken; + this.basePath = configurationParameters.basePath; + this.withCredentials = configurationParameters.withCredentials; + this.encoder = configurationParameters.encoder; + if (configurationParameters.credentials) { + this.credentials = configurationParameters.credentials; + } + else { + this.credentials = {}; + } + + // init default api_key credential + if (!this.credentials['api_key']) { + this.credentials['api_key'] = () => { + if (this.apiKeys === null || this.apiKeys === undefined) { + return undefined; + } else { + return this.apiKeys['api_key'] || this.apiKeys['api_key']; + } + }; + } + + // init default petstore_auth credential + if (!this.credentials['petstore_auth']) { + this.credentials['petstore_auth'] = () => { + return typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + }; + } + } + + /** + * Select the correct content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param contentTypes - the array of content types that are available for selection + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderContentType (contentTypes: string[]): string | undefined { + if (contentTypes.length === 0) { + return undefined; + } + + const type = contentTypes.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return contentTypes[0]; + } + return type; + } + + /** + * Select the correct accept content-type to use for a request. + * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. + * If no content type is found return the first found type if the contentTypes is not empty + * @param accepts - the array of content types that are available for selection. + * @returns the selected content-type or undefined if no selection could be made. + */ + public selectHeaderAccept(accepts: string[]): string | undefined { + if (accepts.length === 0) { + return undefined; + } + + const type = accepts.find((x: string) => this.isJsonMime(x)); + if (type === undefined) { + return accepts[0]; + } + return type; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } + + public lookupCredential(key: string): string | undefined { + const value = this.credentials[key]; + return typeof value === 'function' + ? value() + : value; + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/encoder.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/encoder.ts new file mode 100644 index 00000000000..138c4d5cf2c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/encoder.ts @@ -0,0 +1,20 @@ +import { HttpParameterCodec } from '@angular/common/http'; + +/** + * Custom HttpParameterCodec + * Workaround for https://github.com/angular/angular/issues/18261 + */ +export class CustomHttpParameterCodec implements HttpParameterCodec { + encodeKey(k: string): string { + return encodeURIComponent(k); + } + encodeValue(v: string): string { + return encodeURIComponent(v); + } + decodeKey(k: string): string { + return decodeURIComponent(k); + } + decodeValue(v: string): string { + return decodeURIComponent(v); + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/git_push.sh b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/git_push.sh new file mode 100644 index 00000000000..f53a75d4fab --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/git_push.sh @@ -0,0 +1,57 @@ +#!/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-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts new file mode 100644 index 00000000000..c312b70fa3e --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/index.ts @@ -0,0 +1,5 @@ +export * from './api/api'; +export * from './model/models'; +export * from './variables'; +export * from './configuration'; +export * from './api.module'; \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/apiResponse.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/apiResponse.ts new file mode 100644 index 00000000000..682ba478921 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/apiResponse.ts @@ -0,0 +1,22 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * Describes the result of uploading an image resource + */ +export interface ApiResponse { + code?: number; + type?: string; + message?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/category.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/category.ts new file mode 100644 index 00000000000..b988b6827a0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/category.ts @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * A category for a pet + */ +export interface Category { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/models.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/models.ts new file mode 100644 index 00000000000..8607c5dabd0 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/models.ts @@ -0,0 +1,6 @@ +export * from './apiResponse'; +export * from './category'; +export * from './order'; +export * from './pet'; +export * from './tag'; +export * from './user'; diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/order.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/order.ts new file mode 100644 index 00000000000..a29bebe4906 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/order.ts @@ -0,0 +1,37 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * An order for a pets from the pet store + */ +export interface Order { + id?: number; + petId?: number; + quantity?: number; + shipDate?: string; + /** + * Order Status + */ + status?: Order.StatusEnum; + complete?: boolean; +} +export namespace Order { + export type StatusEnum = 'placed' | 'approved' | 'delivered'; + export const StatusEnum = { + Placed: 'placed' as StatusEnum, + Approved: 'approved' as StatusEnum, + Delivered: 'delivered' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/pet.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/pet.ts new file mode 100644 index 00000000000..e0404395f91 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/pet.ts @@ -0,0 +1,39 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ +import { Category } from './category'; +import { Tag } from './tag'; + + +/** + * A pet for sale in the pet store + */ +export interface Pet { + id?: number; + category?: Category; + name: string; + photoUrls: Array; + tags?: Array; + /** + * pet status in the store + */ + status?: Pet.StatusEnum; +} +export namespace Pet { + export type StatusEnum = 'available' | 'pending' | 'sold'; + export const StatusEnum = { + Available: 'available' as StatusEnum, + Pending: 'pending' as StatusEnum, + Sold: 'sold' as StatusEnum + }; +} + + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/tag.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/tag.ts new file mode 100644 index 00000000000..b6ff210e8df --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/tag.ts @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * A tag for a pet + */ +export interface Tag { + id?: number; + name?: string; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/user.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/user.ts new file mode 100644 index 00000000000..fce51005300 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/model/user.ts @@ -0,0 +1,30 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * 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. + */ + + +/** + * A User who is purchasing from the pet store + */ +export interface User { + id?: number; + username?: string; + firstName?: string; + lastName?: string; + email?: string; + password?: string; + phone?: string; + /** + * User Status + */ + userStatus?: number; +} + diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/ng-package.json b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/ng-package.json new file mode 100644 index 00000000000..3b17900dc9c --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/ng-package.json @@ -0,0 +1,6 @@ +{ + "$schema": "./node_modules/ng-packagr/ng-package.schema.json", + "lib": { + "entryFile": "index.ts" + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/package.json b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/package.json new file mode 100644 index 00000000000..a00df3cd562 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/package.json @@ -0,0 +1,34 @@ +{ + "name": "@openapitools/typescript-angular-petstore", + "version": "1.0.0", + "description": "OpenAPI client for @openapitools/typescript-angular-petstore", + "author": "OpenAPI-Generator Contributors", + "keywords": [ + "openapi-client", + "openapi-generator" + ], + "license": "Unlicense", + "scripts": { + "build": "ng-packagr -p ng-package.json" + }, + "peerDependencies": { + "@angular/core": "^13.0.1", + "rxjs": "^7.4.0" + }, + "devDependencies": { + "@angular/common": "^13.0.1", + "@angular/compiler": "^13.0.1", + "@angular/compiler-cli": "^13.0.1", + "@angular/core": "^13.0.1", + "@angular/platform-browser": "^13.0.1", + "ng-packagr": "^13.0.3", + "reflect-metadata": "^0.1.3", + "rxjs": "^7.4.0", + "tsickle": "^0.43.0", + "typescript": ">=4.4.2 <4.5.0", + "zone.js": "^0.11.4" + }, + "publishConfig": { + "registry": "https://skimdb.npmjs.com/registry" + } +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/tsconfig.json b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/tsconfig.json new file mode 100644 index 00000000000..fd2abf8a2ad --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "emitDecoratorMetadata": true, + "experimentalDecorators": true, + "noImplicitAny": false, + "suppressImplicitAnyIndexErrors": true, + "target": "es6", + "module": "es6", + "moduleResolution": "node", + "removeComments": true, + "sourceMap": true, + "outDir": "./dist", + "noLib": false, + "declaration": true, + "lib": [ "es6", "dom" ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "node_modules", + "dist" + ], + "filesGlob": [ + "./model/*.ts", + "./api/*.ts" + ] +} diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/variables.ts b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/variables.ts new file mode 100644 index 00000000000..6fe58549f39 --- /dev/null +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/variables.ts @@ -0,0 +1,9 @@ +import { InjectionToken } from '@angular/core'; + +export const BASE_PATH = new InjectionToken('basePath'); +export const COLLECTION_FORMATS = { + 'csv': ',', + 'tsv': ' ', + 'ssv': ' ', + 'pipes': '|' +} From 836e40f1d22fca7466be20fa55b64da3e1c42db8 Mon Sep 17 00:00:00 2001 From: Justin Black Date: Fri, 3 Dec 2021 10:21:36 -0800 Subject: [PATCH 47/61] Fixes CodegenMediaType schema baseName (#11030) --- .../java/org/openapitools/codegen/DefaultCodegen.java | 8 ++++++-- .../java/org/openapitools/codegen/DefaultCodegenTest.java | 4 ++++ 2 files changed, 10 insertions(+), 2 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 046d8609d3c..042ffc089c3 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 @@ -6558,6 +6558,10 @@ public class DefaultCodegen implements CodegenConfig { codegenParameter.pattern = toRegularExpression(schema.getPattern()); } + protected String toMediaTypeSchemaName(String contentType) { + return toModelName(contentType + "Schema"); + } + protected LinkedHashMap getContent(Content content, Set imports) { if (content == null) { return null; @@ -6605,9 +6609,9 @@ public class DefaultCodegen implements CodegenConfig { ceMap.put(propName, ce); } } - CodegenProperty schemaProp = fromProperty("schema", mt.getSchema()); - CodegenMediaType codegenMt = new CodegenMediaType(schemaProp, ceMap); String contentType = contentEntry.getKey(); + CodegenProperty schemaProp = fromProperty(toMediaTypeSchemaName(contentType), mt.getSchema()); + CodegenMediaType codegenMt = new CodegenMediaType(schemaProp, ceMap); cmtContent.put(contentType, codegenMt); } return cmtContent; diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index 28748850f1b..87486da4c36 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -3922,11 +3922,13 @@ public class DefaultCodegenTest { CodegenMediaType mt = content.get("application/json"); assertNull(mt.getEncoding()); CodegenProperty cp = mt.getSchema(); + assertEquals(cp.baseName, "ApplicationJsonSchema"); assertNotNull(cp); mt = content.get("text/plain"); assertNull(mt.getEncoding()); cp = mt.getSchema(); + assertEquals(cp.baseName, "TextPlainSchema"); assertNotNull(cp); // Note: the inline model resolver has a bug for this use case; it extracts an inline request body into a component // but the schema it references is not string type @@ -3940,11 +3942,13 @@ public class DefaultCodegenTest { mt = content.get("application/json"); assertNull(mt.getEncoding()); cp = mt.getSchema(); + assertEquals(cp.baseName, "ApplicationJsonSchema"); assertEquals(cp.complexType, "coordinates"); mt = content.get("text/plain"); assertNull(mt.getEncoding()); cp = mt.getSchema(); + assertEquals(cp.baseName, "TextPlainSchema"); assertTrue(cp.isString); } } From 37190357879efc838faf881f66a0dd3b6311b67d Mon Sep 17 00:00:00 2001 From: Tal Kirshboim Date: Sat, 4 Dec 2021 05:56:40 +0100 Subject: [PATCH 48/61] Fix HTTP client configuration object freezing issue on iOS (#11012) --- .../infrastructure/ApiClient.kt.mustache | 13 +++++++++---- .../openapitools/client/infrastructure/ApiClient.kt | 13 +++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache index 84836e45e7e..470c4bc2926 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache @@ -34,15 +34,20 @@ import {{packageName}}.auth.* KotlinxSerializer(json).ignoreOutgoingContent() } - private val defaultHttpClientConfig: (HttpClientConfig<*>) -> Unit by lazy { - val jsonConfig: JsonFeature.Config.() -> Unit = { this.serializer = this@ApiClient.serializer } - { it.install(JsonFeature, jsonConfig) } + private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { + { + // Hold a reference to the serializer to avoid freezing the entire ApiClient instance + // when the JsonFeature is configured. + val serializerReference = serializer + it.install(JsonFeature) { serializer = serializerReference } + httpClientConfig?.invoke(it) + } } private val client: HttpClient by lazy { - val clientConfig: (HttpClientConfig<*>) -> Unit = httpClientConfig ?: defaultHttpClientConfig httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) } + {{#hasAuthMethods}} private val authentications: kotlin.collections.Map by lazy { mapOf({{#authMethods}}{{#isBasic}}{{#isBasicBasic}} diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 4fbb14f3f45..a6ec2640afc 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -34,15 +34,20 @@ open class ApiClient( KotlinxSerializer(json).ignoreOutgoingContent() } - private val defaultHttpClientConfig: (HttpClientConfig<*>) -> Unit by lazy { - val jsonConfig: JsonFeature.Config.() -> Unit = { this.serializer = this@ApiClient.serializer } - { it.install(JsonFeature, jsonConfig) } + private val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { + { + // Hold a reference to the serializer to avoid freezing the entire ApiClient instance + // when the JsonFeature is configured. + val serializerReference = serializer + it.install(JsonFeature) { serializer = serializerReference } + httpClientConfig?.invoke(it) + } } private val client: HttpClient by lazy { - val clientConfig: (HttpClientConfig<*>) -> Unit = httpClientConfig ?: defaultHttpClientConfig httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) } + private val authentications: kotlin.collections.Map by lazy { mapOf( "api_key" to ApiKeyAuth("header", "api_key"), From 6bc739091473d974187fa14ea669de7aee9f057d Mon Sep 17 00:00:00 2001 From: Abrhm7786 <82376602+Abrhm7786@users.noreply.github.com> Date: Sat, 4 Dec 2021 05:05:30 +0000 Subject: [PATCH 49/61] Azure functions (#11020) * New branch * Added test class for functions server * Logger should not be static * Added csharp-netcore-functions to docs/generators * Added csharp-netcore-functions to generators.md * Removes sln and csproj --- docs/generators.md | 1 + docs/generators/csharp-netcore-functions.md | 300 +++++ .../CSharpNetCoreReducedClientCodegen.java | 1151 +++++++++++++++++ .../CsharpNetcoreFunctionsServerCodegen.java | 82 ++ .../org.openapitools.codegen.CodegenConfig | 1 + .../AbstractOpenAPISchema.mustache | 68 + .../ApiClient.mustache | 867 +++++++++++++ .../ApiException.mustache | 60 + .../ApiResponse.mustache | 158 +++ .../AssemblyInfo.mustache | 40 + .../ClientUtils.mustache | 239 ++++ .../Configuration.mustache | 574 ++++++++ .../ExceptionFactory.mustache | 14 + .../GlobalConfiguration.mustache | 59 + .../HttpMethod.mustache | 25 + .../HttpSigningConfiguration.mustache | 757 +++++++++++ .../IApiAccessor.mustache | 29 + .../IAsynchronousClient.mustache | 92 ++ .../IReadableConfiguration.mustache | 114 ++ .../ISynchronousClient.mustache | 85 ++ .../JsonSubTypesTests.mustache | 125 ++ .../Multimap.mustache | 287 ++++ .../OpenAPIDateConverter.mustache | 21 + .../csharp-netcore-functions/README.mustache | 270 ++++ .../ReadOnlyDictionary.mustache | 137 ++ .../RequestOptions.mustache | 66 + .../RetryConfiguration.mustache | 39 + .../Solution.mustache | 27 + .../TestProject.mustache | 36 + .../WebRequestPathBuilder.mustache | 44 + .../csharp-netcore-functions/api.mustache | 626 +++++++++ .../csharp-netcore-functions/api_doc.mustache | 134 ++ .../api_test.mustache | 73 ++ .../appveyor.mustache | 9 + .../functions.mustache | 28 + .../git_push.sh.mustache | 58 + .../gitignore.mustache | 362 ++++++ .../libraries/httpclient/ApiClient.mustache | 739 +++++++++++ .../httpclient/FileParameter.mustache | 54 + .../httpclient/RequestOptions.mustache | 66 + .../libraries/httpclient/api.mustache | 724 +++++++++++ .../libraries/httpclient/model.mustache | 48 + .../csharp-netcore-functions/model.mustache | 47 + .../modelAnyOf.mustache | 227 ++++ .../modelEnum.mustache | 30 + .../modelGeneric.mustache | 456 +++++++ .../modelInnerEnum.mustache | 26 + .../modelOneOf.mustache | 264 ++++ .../model_doc.mustache | 22 + .../model_test.mustache | 81 ++ .../netcore_project.mustache | 44 + .../netcore_testproject.mustache | 20 + .../csharp-netcore-functions/nuspec.mustache | 52 + .../partial_header.mustache | 17 + .../pathParam.mustache | 1 + .../csharp-netcore-functions/project.mustache | 12 + .../visibility.mustache | 1 + ...harpNetcoreFunctionsServerCodegenTest.java | 40 + 58 files changed, 10029 insertions(+) create mode 100644 docs/generators/csharp-netcore-functions.md create mode 100644 modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java create mode 100644 modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/AbstractOpenAPISchema.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiClient.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiException.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiResponse.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/AssemblyInfo.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/ClientUtils.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/Configuration.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/ExceptionFactory.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/GlobalConfiguration.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpMethod.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpSigningConfiguration.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/IApiAccessor.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/IAsynchronousClient.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/IReadableConfiguration.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/ISynchronousClient.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/JsonSubTypesTests.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/Multimap.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/OpenAPIDateConverter.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/README.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/ReadOnlyDictionary.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/RequestOptions.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/RetryConfiguration.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/Solution.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/TestProject.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/WebRequestPathBuilder.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/api.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_doc.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_test.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/appveyor.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/functions.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/git_push.sh.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/gitignore.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/FileParameter.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/RequestOptions.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/api.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/model.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/model.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelAnyOf.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelEnum.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelInnerEnum.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelOneOf.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_doc.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_test.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_project.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_testproject.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/nuspec.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/partial_header.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/pathParam.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/project.mustache create mode 100644 modules/openapi-generator/src/main/resources/csharp-netcore-functions/visibility.mustache create mode 100644 modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp-netcore-functions/CsharpNetcoreFunctionsServerCodegenTest.java diff --git a/docs/generators.md b/docs/generators.md index ed80e860e49..088acf1b859 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -85,6 +85,7 @@ The following generators are available: * [cpp-pistache-server](generators/cpp-pistache-server.md) * [cpp-qt-qhttpengine-server](generators/cpp-qt-qhttpengine-server.md) * [cpp-restbed-server](generators/cpp-restbed-server.md) +* [csharp-netcore-functions](generators/csharp-netcore-functions.md) * [csharp-nancyfx](generators/csharp-nancyfx.md) * [erlang-server](generators/erlang-server.md) * [fsharp-functions (beta)](generators/fsharp-functions.md) diff --git a/docs/generators/csharp-netcore-functions.md b/docs/generators/csharp-netcore-functions.md new file mode 100644 index 00000000000..50ec49b34a1 --- /dev/null +++ b/docs/generators/csharp-netcore-functions.md @@ -0,0 +1,300 @@ +--- +title: Config Options for csharp-netcore-functions +sidebar_label: csharp-netcore-functions +--- + +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|caseInsensitiveResponseHeaders|Make API response's headers case-insensitive| |false| +|conditionalSerialization|Serialize only those properties which are initialized by user, accepted values are true or false, default value is false.| |false| +|disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|

    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| +|hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| +|interfacePrefix|Prefix interfaces with a community standard or widely accepted prefix.| |I| +|library|HTTP library template (sub-template) to use|
    **httpclient**
    HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) (Experimental. May subject to breaking changes without further notice.)
    **restsharp**
    RestSharp (https://github.com/restsharp/RestSharp)
    |restsharp| +|licenseId|The identifier of the license| |null| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |PascalCase| +|netCoreProjectFile|Use the new format (.NET Core) for .NET project files (.csproj).| |false| +|nonPublicApi|Generates code with reduced access modifiers; allows embedding elsewhere without exposing non-public API calls to consumers.| |false| +|nullableReferenceTypes|Use nullable annotations in the project. Only supported on C# 8 / ASP.NET Core 3.0 or newer.| |false| +|optionalAssemblyInfo|Generate AssemblyInfo.cs.| |true| +|optionalEmitDefaultValues|Set DataMember's EmitDefaultValue.| |false| +|optionalMethodArgument|C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).| |true| +|optionalProjectFile|Generate {PackageName}.csproj.| |true| +|packageGuid|The GUID that will be associated with the C# project| |null| +|packageName|C# package name (convention: Title.Case).| |Org.OpenAPITools| +|packageTags|Tags to identify the package| |null| +|packageVersion|C# package version.| |1.0.0| +|releaseNote|Release note, default to 'Minor update'.| |Minor update| +|returnICollection|Return ICollection<T> instead of the concrete type.| |false| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceFolder|source folder for generated code| |src| +|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.0`|
    **netstandard1.3**
    .NET Standard 1.3 compatible
    **netstandard1.4**
    .NET Standard 1.4 compatible
    **netstandard1.5**
    .NET Standard 1.5 compatible
    **netstandard1.6**
    .NET Standard 1.6 compatible
    **netstandard2.0**
    .NET Standard 2.0 compatible
    **netstandard2.1**
    .NET Standard 2.1 compatible
    **netcoreapp2.0**
    .NET Core 2.0 compatible
    **netcoreapp2.1**
    .NET Core 2.1 compatible
    **netcoreapp3.0**
    .NET Core 3.0 compatible
    **netcoreapp3.1**
    .NET Core 3.1 compatible
    **net47**
    .NET Framework 4.7 compatible
    **net5.0**
    .NET 5.0 compatible
    |netstandard2.0| +|useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| +|useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| +|useOneOfDiscriminatorLookup|Use the discriminator's mapping in oneOf to speed up the model lookup. IMPORTANT: Validation (e.g. one and only one match in oneOf's schemas) will be skipped.| |false| +|validatable|Generates self-validatable models.| |true| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|List| +|list|List| +|map|Dictionary| + + +## LANGUAGE PRIMITIVES + +
      +
    • Boolean
    • +
    • Collection
    • +
    • DateTime
    • +
    • DateTime?
    • +
    • DateTimeOffset
    • +
    • DateTimeOffset?
    • +
    • Decimal
    • +
    • Dictionary
    • +
    • Double
    • +
    • Float
    • +
    • Guid
    • +
    • Guid?
    • +
    • ICollection
    • +
    • Int32
    • +
    • Int64
    • +
    • List
    • +
    • Object
    • +
    • String
    • +
    • System.IO.Stream
    • +
    • bool
    • +
    • bool?
    • +
    • byte[]
    • +
    • decimal
    • +
    • decimal?
    • +
    • double
    • +
    • double?
    • +
    • float
    • +
    • float?
    • +
    • int
    • +
    • int?
    • +
    • long
    • +
    • long?
    • +
    • string
    • +
    + +## RESERVED WORDS + +
      +
    • Client
    • +
    • Configuration
    • +
    • Version
    • +
    • abstract
    • +
    • as
    • +
    • base
    • +
    • bool
    • +
    • break
    • +
    • byte
    • +
    • case
    • +
    • catch
    • +
    • char
    • +
    • checked
    • +
    • class
    • +
    • client
    • +
    • const
    • +
    • continue
    • +
    • decimal
    • +
    • default
    • +
    • delegate
    • +
    • do
    • +
    • double
    • +
    • else
    • +
    • enum
    • +
    • event
    • +
    • explicit
    • +
    • extern
    • +
    • false
    • +
    • finally
    • +
    • fixed
    • +
    • float
    • +
    • for
    • +
    • foreach
    • +
    • goto
    • +
    • if
    • +
    • implicit
    • +
    • in
    • +
    • int
    • +
    • interface
    • +
    • internal
    • +
    • is
    • +
    • localVarFileParams
    • +
    • localVarFormParams
    • +
    • localVarHeaderParams
    • +
    • localVarHttpContentType
    • +
    • localVarHttpContentTypes
    • +
    • localVarHttpHeaderAccept
    • +
    • localVarHttpHeaderAccepts
    • +
    • localVarPath
    • +
    • localVarPathParams
    • +
    • localVarPostBody
    • +
    • localVarQueryParams
    • +
    • localVarResponse
    • +
    • localVarStatusCode
    • +
    • lock
    • +
    • long
    • +
    • namespace
    • +
    • new
    • +
    • null
    • +
    • object
    • +
    • operator
    • +
    • out
    • +
    • override
    • +
    • parameter
    • +
    • params
    • +
    • private
    • +
    • protected
    • +
    • public
    • +
    • readonly
    • +
    • ref
    • +
    • return
    • +
    • sbyte
    • +
    • sealed
    • +
    • short
    • +
    • sizeof
    • +
    • stackalloc
    • +
    • static
    • +
    • string
    • +
    • struct
    • +
    • switch
    • +
    • this
    • +
    • throw
    • +
    • true
    • +
    • try
    • +
    • typeof
    • +
    • uint
    • +
    • ulong
    • +
    • unchecked
    • +
    • unsafe
    • +
    • ushort
    • +
    • using
    • +
    • virtual
    • +
    • void
    • +
    • volatile
    • +
    • while
    • +
    + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✓|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✓|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Array|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✓|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✓|OAS2,OAS3 +|Union|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✗|OAS2,OAS3 diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java new file mode 100644 index 00000000000..8f189b444ba --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java @@ -0,0 +1,1151 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * 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. + */ + +package org.openapitools.codegen.languages; + +import com.google.common.collect.ImmutableMap; +import com.samskivert.mustache.Mustache; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.ComposedSchema; +import io.swagger.v3.oas.models.media.Schema; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.utils.ProcessUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.*; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Consumer; +import java.util.stream.Collectors; + +import static org.apache.commons.lang3.StringUtils.isEmpty; +import static org.openapitools.codegen.utils.StringUtils.camelize; +import static org.openapitools.codegen.utils.StringUtils.underscore; + +@SuppressWarnings("Duplicates") +public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { + // Defines the sdk option for targeted frameworks, which differs from targetFramework and targetFrameworkNuget + protected static final String MCS_NET_VERSION_KEY = "x-mcs-sdk"; + protected static final String SUPPORTS_UWP = "supportsUWP"; + protected static final String SUPPORTS_RETRY = "supportsRetry"; + + protected static final String NET_STANDARD = "netStandard"; + + // HTTP libraries + protected static final String RESTSHARP = "restsharp"; + protected static final String HTTPCLIENT = "httpclient"; + + // Project Variable, determined from target framework. Not intended to be user-settable. + protected static final String TARGET_FRAMEWORK_IDENTIFIER = "targetFrameworkIdentifier"; + // Project Variable, determined from target framework. Not intended to be user-settable. + protected static final String TARGET_FRAMEWORK_VERSION = "targetFrameworkVersion"; + + @SuppressWarnings("hiding") + private final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); + private static final List frameworkStrategies = Arrays.asList( + FrameworkStrategy.NETSTANDARD_1_3, + FrameworkStrategy.NETSTANDARD_1_4, + FrameworkStrategy.NETSTANDARD_1_5, + FrameworkStrategy.NETSTANDARD_1_6, + FrameworkStrategy.NETSTANDARD_2_0, + FrameworkStrategy.NETSTANDARD_2_1, + FrameworkStrategy.NETCOREAPP_2_0, + FrameworkStrategy.NETCOREAPP_2_1, + FrameworkStrategy.NETCOREAPP_3_0, + FrameworkStrategy.NETCOREAPP_3_1, + FrameworkStrategy.NETFRAMEWORK_4_7, + FrameworkStrategy.NET_5_0 + ); + private static FrameworkStrategy defaultFramework = FrameworkStrategy.NETSTANDARD_2_0; + protected final Map frameworks; + protected String packageGuid = "{" + java.util.UUID.randomUUID().toString().toUpperCase(Locale.ROOT) + "}"; + protected String clientPackage = "Org.OpenAPITools.Client"; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + + // Defines TargetFrameworkVersion in csproj files + protected String targetFramework = defaultFramework.name; + protected String testTargetFramework = defaultFramework.testTargetFramework; + + // Defines nuget identifiers for target framework + protected String targetFrameworkNuget = targetFramework; + + protected boolean supportsRetry = Boolean.TRUE; + protected boolean supportsAsync = Boolean.TRUE; + protected boolean netStandard = Boolean.FALSE; + + protected boolean validatable = Boolean.TRUE; + protected Map regexModifiers; + // By default, generated code is considered public + protected boolean nonPublicApi = Boolean.FALSE; + + protected boolean caseInsensitiveResponseHeaders = Boolean.FALSE; + protected String releaseNote = "Minor update"; + protected String licenseId; + protected String packageTags; + protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup + + protected boolean needsCustomHttpMethod = false; + protected boolean needsUriBuilder = false; + + public CSharpNetCoreReducedClientCodegen() { + super(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .securityFeatures(EnumSet.of( + SecurityFeature.OAuth2_Implicit, + SecurityFeature.BasicAuth, + SecurityFeature.ApiKey + )) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .includeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .includeParameterFeatures( + ParameterFeature.Cookie + ) + .includeClientModificationFeatures( + ClientModificationFeature.BasePath, + ClientModificationFeature.UserAgent + ) + ); + + // mapped non-nullable type without ? + typeMapping = new HashMap(); + typeMapping.put("string", "string"); + typeMapping.put("binary", "byte[]"); + typeMapping.put("ByteArray", "byte[]"); + typeMapping.put("boolean", "bool"); + typeMapping.put("integer", "int"); + typeMapping.put("float", "float"); + typeMapping.put("long", "long"); + typeMapping.put("double", "double"); + typeMapping.put("number", "decimal"); + typeMapping.put("decimal", "decimal"); + typeMapping.put("DateTime", "DateTime"); + typeMapping.put("date", "DateTime"); + typeMapping.put("file", "System.IO.Stream"); + typeMapping.put("array", "List"); + typeMapping.put("list", "List"); + typeMapping.put("map", "Dictionary"); + typeMapping.put("object", "Object"); + typeMapping.put("UUID", "Guid"); + typeMapping.put("URI", "string"); + typeMapping.put("AnyType", "Object"); + + setSupportNullable(Boolean.TRUE); + hideGenerationTimestamp = Boolean.TRUE; + supportsInheritance = true; + modelTemplateFiles.put("model.mustache", ".cs"); + apiTemplateFiles.put("api.mustache", ".cs"); + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + embeddedTemplateDir = templateDir = "csharp-netcore"; + + cliOptions.clear(); + + // CLI options + addOption(CodegenConstants.PACKAGE_NAME, + "C# package name (convention: Title.Case).", + this.packageName); + + addOption(CodegenConstants.PACKAGE_VERSION, + "C# package version.", + this.packageVersion); + + addOption(CodegenConstants.SOURCE_FOLDER, + CodegenConstants.SOURCE_FOLDER_DESC, + sourceFolder); + + addOption(CodegenConstants.OPTIONAL_PROJECT_GUID, + CodegenConstants.OPTIONAL_PROJECT_GUID_DESC, + null); + + addOption(CodegenConstants.INTERFACE_PREFIX, + CodegenConstants.INTERFACE_PREFIX_DESC, + interfacePrefix); + + addOption(CodegenConstants.LICENSE_ID, + CodegenConstants.LICENSE_ID_DESC, + this.licenseId); + + addOption(CodegenConstants.RELEASE_NOTE, + CodegenConstants.RELEASE_NOTE_DESC, + this.releaseNote); + + addOption(CodegenConstants.PACKAGE_TAGS, + CodegenConstants.PACKAGE_TAGS_DESC, + this.packageTags); + + CliOption framework = new CliOption( + CodegenConstants.DOTNET_FRAMEWORK, + CodegenConstants.DOTNET_FRAMEWORK_DESC + ); + + CliOption disallowAdditionalPropertiesIfNotPresentOpt = CliOption.newBoolean( + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, + CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_DESC).defaultValue(Boolean.TRUE.toString()); + Map disallowAdditionalPropertiesIfNotPresentOpts = new HashMap<>(); + disallowAdditionalPropertiesIfNotPresentOpts.put("false", + "The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications."); + disallowAdditionalPropertiesIfNotPresentOpts.put("true", + "Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default."); + disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts); + cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt); + this.setDisallowAdditionalPropertiesIfNotPresent(true); + + ImmutableMap.Builder frameworkBuilder = new ImmutableMap.Builder<>(); + for (FrameworkStrategy frameworkStrategy : frameworkStrategies) { + frameworkBuilder.put(frameworkStrategy.name, frameworkStrategy.description); + } + + frameworks = frameworkBuilder.build(); + + framework.defaultValue(this.targetFramework); + framework.setEnum(frameworks); + cliOptions.add(framework); + + CliOption modelPropertyNaming = new CliOption(CodegenConstants.MODEL_PROPERTY_NAMING, CodegenConstants.MODEL_PROPERTY_NAMING_DESC); + cliOptions.add(modelPropertyNaming.defaultValue("PascalCase")); + + // CLI Switches + addSwitch(CodegenConstants.NULLABLE_REFERENCE_TYPES, + CodegenConstants.NULLABLE_REFERENCE_TYPES_DESC, + this.nullReferenceTypesFlag); + + addSwitch(CodegenConstants.HIDE_GENERATION_TIMESTAMP, + CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC, + this.hideGenerationTimestamp); + + addSwitch(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, + CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG_DESC, + this.sortParamsByRequiredFlag); + + addSwitch(CodegenConstants.USE_DATETIME_OFFSET, + CodegenConstants.USE_DATETIME_OFFSET_DESC, + this.useDateTimeOffsetFlag); + + addSwitch(CodegenConstants.USE_COLLECTION, + CodegenConstants.USE_COLLECTION_DESC, + this.useCollection); + + addSwitch(CodegenConstants.RETURN_ICOLLECTION, + CodegenConstants.RETURN_ICOLLECTION_DESC, + this.returnICollection); + + addSwitch(CodegenConstants.OPTIONAL_METHOD_ARGUMENT, + "C# Optional method argument, e.g. void square(int x=10) (.net 4.0+ only).", + this.optionalMethodArgumentFlag); + + addSwitch(CodegenConstants.OPTIONAL_ASSEMBLY_INFO, + CodegenConstants.OPTIONAL_ASSEMBLY_INFO_DESC, + this.optionalAssemblyInfoFlag); + + addSwitch(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, + CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC, + this.optionalEmitDefaultValuesFlag); + + addSwitch(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION, + CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION_DESC, + this.conditionalSerialization); + + addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, + CodegenConstants.OPTIONAL_PROJECT_FILE_DESC, + this.optionalProjectFileFlag); + + // NOTE: This will reduce visibility of all public members in templates. Users can use InternalsVisibleTo + // https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute(v=vs.110).aspx + // to expose to shared code if the generated code is not embedded into another project. Otherwise, users of codegen + // should rely on default public visibility. + addSwitch(CodegenConstants.NON_PUBLIC_API, + CodegenConstants.NON_PUBLIC_API_DESC, + this.nonPublicApi); + + addSwitch(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, + CodegenConstants.ALLOW_UNICODE_IDENTIFIERS_DESC, + this.allowUnicodeIdentifiers); + + addSwitch(CodegenConstants.NETCORE_PROJECT_FILE, + CodegenConstants.NETCORE_PROJECT_FILE_DESC, + this.netCoreProjectFileFlag); + + addSwitch(CodegenConstants.VALIDATABLE, + CodegenConstants.VALIDATABLE_DESC, + this.validatable); + + addSwitch(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, + CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC, + this.caseInsensitiveResponseHeaders); + + addSwitch(CodegenConstants.CASE_INSENSITIVE_RESPONSE_HEADERS, + CodegenConstants.CASE_INSENSITIVE_RESPONSE_HEADERS_DESC, + this.caseInsensitiveResponseHeaders); + + regexModifiers = new HashMap<>(); + regexModifiers.put('i', "IgnoreCase"); + regexModifiers.put('m', "Multiline"); + regexModifiers.put('s', "Singleline"); + regexModifiers.put('x', "IgnorePatternWhitespace"); + + supportedLibraries.put(HTTPCLIENT, "HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) " + + "(Experimental. May subject to breaking changes without further notice.)"); + supportedLibraries.put(RESTSHARP, "RestSharp (https://github.com/restsharp/RestSharp)"); + + CliOption libraryOption = new CliOption(CodegenConstants.LIBRARY, "HTTP library template (sub-template) to use"); + libraryOption.setEnum(supportedLibraries); + // set RESTSHARP as the default + libraryOption.setDefault(RESTSHARP); + cliOptions.add(libraryOption); + setLibrary(RESTSHARP); + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/" + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String apiTestFileFolder() { + return outputFolder + File.separator + testFolder + File.separator + testPackageName() + File.separator + apiPackage(); + } + + @Override + public CodegenModel fromModel(String name, Schema model) { + Map allDefinitions = ModelUtils.getSchemas(this.openAPI); + CodegenModel codegenModel = super.fromModel(name, model); + if (allDefinitions != null && codegenModel != null && codegenModel.parent != null) { + final Schema parentModel = allDefinitions.get(toModelName(codegenModel.parent)); + if (parentModel != null) { + final CodegenModel parentCodegenModel = super.fromModel(codegenModel.parent, parentModel); + if (codegenModel.hasEnums) { + codegenModel = this.reconcileInlineEnums(codegenModel, parentCodegenModel); + } + + Map propertyHash = new HashMap<>(codegenModel.vars.size()); + for (final CodegenProperty property : codegenModel.vars) { + propertyHash.put(property.name, property); + } + + for (final CodegenProperty property : codegenModel.readWriteVars) { + if (property.defaultValue == null && parentCodegenModel.discriminator != null && property.name.equals(parentCodegenModel.discriminator.getPropertyName())) { + property.defaultValue = "\"" + name + "\""; + } + } + + CodegenProperty last = null; + for (final CodegenProperty property : parentCodegenModel.vars) { + // helper list of parentVars simplifies templating + if (!propertyHash.containsKey(property.name)) { + final CodegenProperty parentVar = property.clone(); + parentVar.isInherited = true; + last = parentVar; + LOGGER.debug("adding parent variable {}", property.name); + codegenModel.parentVars.add(parentVar); + } + } + } + } + + // Cleanup possible duplicates. Currently, readWriteVars can contain the same property twice. May or may not be isolated to C#. + if (codegenModel != null && codegenModel.readWriteVars != null && codegenModel.readWriteVars.size() > 1) { + int length = codegenModel.readWriteVars.size() - 1; + for (int i = length; i > (length / 2); i--) { + final CodegenProperty codegenProperty = codegenModel.readWriteVars.get(i); + // If the property at current index is found earlier in the list, remove this last instance. + if (codegenModel.readWriteVars.indexOf(codegenProperty) < i) { + codegenModel.readWriteVars.remove(i); + } + } + } + + return codegenModel; + } + + @Override + public String getHelp() { + return "Generates a C# client library (.NET Standard, .NET Core)."; + } + + public String getModelPropertyNaming() { + return this.modelPropertyNaming; + } + + public void setModelPropertyNaming(String naming) { + if ("original".equals(naming) || "camelCase".equals(naming) || + "PascalCase".equals(naming) || "snake_case".equals(naming)) { + this.modelPropertyNaming = naming; + } else { + throw new IllegalArgumentException("Invalid model property naming '" + + naming + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } + } + + @Override + public String getName() { + return "csharp-netcore"; + } + + public String getNameUsingModelPropertyNaming(String name) { + switch (CodegenConstants.MODEL_PROPERTY_NAMING_TYPE.valueOf(getModelPropertyNaming())) { + case original: + return name; + case camelCase: + return camelize(name, true); + case PascalCase: + return camelize(name); + case snake_case: + return underscore(name); + default: + throw new IllegalArgumentException("Invalid model property naming '" + + name + "'. Must be 'original', 'camelCase', " + + "'PascalCase' or 'snake_case'"); + } + } + + @Override + public String getNullableType(Schema p, String type) { + if (languageSpecificPrimitives.contains(type)) { + if (isSupportNullable() && ModelUtils.isNullable(p) && nullableType.contains(type)) { + return type + "?"; + } else { + return type; + } + } else { + return null; + } + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + public boolean isNonPublicApi() { + return nonPublicApi; + } + + public void setNonPublicApi(final boolean nonPublicApi) { + this.nonPublicApi = nonPublicApi; + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + "/" + modelDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelTestFileFolder() { + return outputFolder + File.separator + testFolder + File.separator + testPackageName() + File.separator + modelPackage(); + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + postProcessPattern(property.pattern, property.vendorExtensions); + postProcessEmitDefaultValue(property.vendorExtensions); + + super.postProcessModelProperty(model, property); + } + + @Override + public void postProcessParameter(CodegenParameter parameter) { + postProcessPattern(parameter.pattern, parameter.vendorExtensions); + postProcessEmitDefaultValue(parameter.vendorExtensions); + super.postProcessParameter(parameter); + } + + /* + * The pattern spec follows the Perl convention and style of modifiers. .NET + * does not support this syntax directly so we need to convert the pattern to a .NET compatible + * format and apply modifiers in a compatible way. + * See https://msdn.microsoft.com/en-us/library/yd1hzczs(v=vs.110).aspx for .NET options. + */ + public void postProcessPattern(String pattern, Map vendorExtensions) { + if (pattern != null) { + int i = pattern.lastIndexOf('/'); + + //Must follow Perl /pattern/modifiers convention + if (pattern.charAt(0) != '/' || i < 2) { + throw new IllegalArgumentException("Pattern must follow the Perl " + + "/pattern/modifiers convention. " + pattern + " is not valid."); + } + + String regex = pattern.substring(1, i).replace("'", "\'").replace("\"", "\"\""); + List modifiers = new ArrayList(); + + // perl requires an explicit modifier to be culture specific and .NET is the reverse. + modifiers.add("CultureInvariant"); + + for (char c : pattern.substring(i).toCharArray()) { + if (regexModifiers.containsKey(c)) { + String modifier = regexModifiers.get(c); + modifiers.add(modifier); + } else if (c == 'l') { + modifiers.remove("CultureInvariant"); + } + } + + vendorExtensions.put("x-regex", regex); + vendorExtensions.put("x-modifiers", modifiers); + } + } + + public void postProcessEmitDefaultValue(Map vendorExtensions) { + vendorExtensions.put("x-emit-default-value", optionalEmitDefaultValuesFlag); + } + + @Override + public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { + // To avoid unexpected behaviors when options are passed programmatically such as { "supportsAsync": "" } + return super.processCompiler(compiler).emptyStringIsFalse(true); + } + + @Override + public void processOpts() { + this.setLegacyDiscriminatorBehavior(false); + + super.processOpts(); + + /* + * NOTE: When supporting boolean additionalProperties, you should read the value and write it back as a boolean. + * This avoids oddities where additionalProperties contains "false" rather than false, which will cause the + * templating engine to behave unexpectedly. + * + * Use the pattern: + * if (additionalProperties.containsKey(prop)) convertPropertyToBooleanAndWriteBack(prop); + */ + + if (additionalProperties.containsKey(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT)) { + this.setDisallowAdditionalPropertiesIfNotPresent(Boolean.parseBoolean(additionalProperties + .get(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT).toString())); + } + + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES)) { + setOptionalEmitDefaultValuesFlag(convertPropertyToBooleanAndWriteBack(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES)); + } else { + additionalProperties.put(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, optionalEmitDefaultValuesFlag); + } + + if (additionalProperties.containsKey(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION)) { + setConditionalSerialization(convertPropertyToBooleanAndWriteBack(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION)); + } else { + additionalProperties.put(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION, conditionalSerialization); + } + + if (additionalProperties.containsKey(CodegenConstants.MODEL_PROPERTY_NAMING)) { + setModelPropertyNaming((String) additionalProperties.get(CodegenConstants.MODEL_PROPERTY_NAMING)); + } + + if (isEmpty(apiPackage)) { + setApiPackage("Api"); + } + if (isEmpty(modelPackage)) { + setModelPackage("Model"); + } + + clientPackage = "Client"; + + if (RESTSHARP.equals(getLibrary())) { + additionalProperties.put("useRestSharp", true); + needsCustomHttpMethod = true; + } else if (HTTPCLIENT.equals(getLibrary())) { + setLibrary(HTTPCLIENT); + additionalProperties.put("useHttpClient", true); + needsUriBuilder = true; + } else { + throw new RuntimeException("Invalid HTTP library " + getLibrary() + ". Only restsharp, httpclient are supported."); + } + + String inputFramework = (String) additionalProperties.getOrDefault(CodegenConstants.DOTNET_FRAMEWORK, defaultFramework.name); + String[] frameworks; + List strategies = new ArrayList<>(); + + if (inputFramework.contains(";")) { + // multiple target framework + frameworks = inputFramework.split(";"); + additionalProperties.put("multiTarget", true); + } else { + // just a single value + frameworks = new String [] {inputFramework}; + } + + for (String framework : frameworks) { + boolean strategyMatched = false; + for (FrameworkStrategy frameworkStrategy : frameworkStrategies) { + if (framework.equals(frameworkStrategy.name)) { + strategies.add(frameworkStrategy); + strategyMatched = true; + } + + if (frameworkStrategy != FrameworkStrategy.NETSTANDARD_2_0 && "restsharp".equals(getLibrary())) { + LOGGER.warn("If using built-in templates, RestSharp only supports netstandard 2.0 or later."); + } + } + + if (!strategyMatched) { + // throws exception if the input targetFramework is invalid + throw new IllegalArgumentException("The input (" + inputFramework + ") contains Invalid .NET framework version: " + + framework + ". List of supported versions: " + + frameworkStrategies.stream() + .map(p -> p.name) + .collect(Collectors.joining(", "))); + } + } + + configureAdditionalPropertiesForFrameworks(additionalProperties, strategies); + setTargetFrameworkNuget(strategies); + setTargetFramework(strategies); + setTestTargetFramework(strategies); + + setSupportsAsync(Boolean.TRUE); + setNetStandard(strategies.stream().anyMatch(p -> Boolean.TRUE.equals(p.isNetStandard))); + + if (!netStandard) { + setNetCoreProjectFileFlag(true); + } + + if (additionalProperties.containsKey(CodegenConstants.GENERATE_PROPERTY_CHANGED)) { + LOGGER.warn("{} is not supported in the .NET Standard generator.", CodegenConstants.GENERATE_PROPERTY_CHANGED); + additionalProperties.remove(CodegenConstants.GENERATE_PROPERTY_CHANGED); + } + + final AtomicReference excludeTests = new AtomicReference<>(); + syncBooleanProperty(additionalProperties, CodegenConstants.EXCLUDE_TESTS, excludeTests::set, false); + + syncStringProperty(additionalProperties, "clientPackage", (s) -> { }, clientPackage); + + syncStringProperty(additionalProperties, CodegenConstants.API_PACKAGE, this::setApiPackage, apiPackage); + syncStringProperty(additionalProperties, CodegenConstants.MODEL_PACKAGE, this::setModelPackage, modelPackage); + syncStringProperty(additionalProperties, CodegenConstants.OPTIONAL_PROJECT_GUID, this::setPackageGuid, packageGuid); + syncStringProperty(additionalProperties, "targetFrameworkNuget", this::setTargetFrameworkNuget, this.targetFrameworkNuget); + syncStringProperty(additionalProperties, "testTargetFramework", this::setTestTargetFramework, this.testTargetFramework); + + syncBooleanProperty(additionalProperties, "netStandard", this::setNetStandard, this.netStandard); + + syncBooleanProperty(additionalProperties, CodegenConstants.VALIDATABLE, this::setValidatable, this.validatable); + syncBooleanProperty(additionalProperties, CodegenConstants.SUPPORTS_ASYNC, this::setSupportsAsync, this.supportsAsync); + syncBooleanProperty(additionalProperties, SUPPORTS_RETRY, this::setSupportsRetry, this.supportsRetry); + syncBooleanProperty(additionalProperties, CodegenConstants.OPTIONAL_METHOD_ARGUMENT, this::setOptionalMethodArgumentFlag, optionalMethodArgumentFlag); + syncBooleanProperty(additionalProperties, CodegenConstants.NON_PUBLIC_API, this::setNonPublicApi, isNonPublicApi()); + syncBooleanProperty(additionalProperties, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, this::setUseOneOfDiscriminatorLookup, this.useOneOfDiscriminatorLookup); + + final String testPackageName = testPackageName(); + String packageFolder = sourceFolder + File.separator + packageName; + String clientPackageDir = packageFolder + File.separator + clientPackage; + String modelPackageDir = packageFolder + File.separator + modelPackage; + String testPackageFolder = testFolder + File.separator + testPackageName; + + additionalProperties.put("testPackageName", testPackageName); + + //Compute the relative path to the bin directory where the external assemblies live + //This is necessary to properly generate the project file + int packageDepth = packageFolder.length() - packageFolder.replace(java.io.File.separator, "").length(); + String binRelativePath = "..\\"; + for (int i = 0; i < packageDepth; i = i + 1) { + binRelativePath += "..\\"; + } + binRelativePath += "vendor"; + additionalProperties.put("binRelativePath", binRelativePath); + + if(HTTPCLIENT.equals(getLibrary())) { + supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs")); + typeMapping.put("file", "FileParameter"); + } + + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); + supportingFiles.add(new SupportingFile("Configuration.mustache", clientPackageDir, "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", clientPackageDir, "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", clientPackageDir, "ApiException.cs")); + supportingFiles.add(new SupportingFile("ApiResponse.mustache", clientPackageDir, "ApiResponse.cs")); + supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", clientPackageDir, "ExceptionFactory.cs")); + supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs")); + supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs")); + if(needsCustomHttpMethod) { + supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs")); + } + if(needsUriBuilder) { + supportingFiles.add(new SupportingFile("WebRequestPathBuilder.mustache", clientPackageDir, "WebRequestPathBuilder.cs")); + } + if (ProcessUtils.hasHttpSignatureMethods(openAPI)) { + supportingFiles.add(new SupportingFile("HttpSigningConfiguration.mustache", clientPackageDir, "HttpSigningConfiguration.cs")); + } + if (supportsAsync) { + supportingFiles.add(new SupportingFile("IAsynchronousClient.mustache", clientPackageDir, "IAsynchronousClient.cs")); + } + supportingFiles.add(new SupportingFile("ISynchronousClient.mustache", clientPackageDir, "ISynchronousClient.cs")); + supportingFiles.add(new SupportingFile("RequestOptions.mustache", clientPackageDir, "RequestOptions.cs")); + supportingFiles.add(new SupportingFile("Multimap.mustache", clientPackageDir, "Multimap.cs")); + + if (supportsRetry) { + supportingFiles.add(new SupportingFile("RetryConfiguration.mustache", clientPackageDir, "RetryConfiguration.cs")); + } + + supportingFiles.add(new SupportingFile("IReadableConfiguration.mustache", + clientPackageDir, "IReadableConfiguration.cs")); + supportingFiles.add(new SupportingFile("GlobalConfiguration.mustache", + clientPackageDir, "GlobalConfiguration.cs")); + + // Only write out test related files if excludeTests is unset or explicitly set to false (see start of this method) + if (Boolean.FALSE.equals(excludeTests.get())) { + modelTestTemplateFiles.put("model_test.mustache", ".cs"); + apiTestTemplateFiles.put("api_test.mustache", ".cs"); + } + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh")); + supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore")); + + supportingFiles.add(new SupportingFile("appveyor.mustache", "", "appveyor.yml")); + supportingFiles.add(new SupportingFile("AbstractOpenAPISchema.mustache", modelPackageDir, "AbstractOpenAPISchema.cs")); + + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + } + + public void setNetStandard(Boolean netStandard) { + this.netStandard = netStandard; + } + + public void setOptionalAssemblyInfoFlag(boolean flag) { + this.optionalAssemblyInfoFlag = flag; + } + + public void setOptionalEmitDefaultValuesFlag(boolean flag) { + this.optionalEmitDefaultValuesFlag = flag; + } + + public void setConditionalSerialization(boolean flag){ + this.conditionalSerialization = flag; + } + + public void setOptionalProjectFileFlag(boolean flag) { + this.optionalProjectFileFlag = flag; + } + + public void setPackageGuid(String packageGuid) { + this.packageGuid = packageGuid; + } + + @Override + public void setPackageName(String packageName) { + this.packageName = packageName; + } + + @Override + public void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + public void setSupportsAsync(Boolean supportsAsync) { + this.supportsAsync = supportsAsync; + } + + public void setSupportsRetry(Boolean supportsRetry) { + this.supportsRetry = supportsRetry; + } + + public void setTargetFramework(String dotnetFramework) { + if (!frameworks.containsKey(dotnetFramework)) { + throw new IllegalArgumentException("Invalid .NET framework version: " + + dotnetFramework + ". List of supported versions: " + + frameworkStrategies.stream() + .map(p -> p.name) + .collect(Collectors.joining(", "))); + } else { + this.targetFramework = dotnetFramework; + } + LOGGER.info("Generating code for .NET Framework {}", this.targetFramework); + } + + public void setTargetFramework(List strategies) { + for (FrameworkStrategy strategy : strategies) { + if (!frameworks.containsKey(strategy.name)) { + throw new IllegalArgumentException("Invalid .NET framework version: " + + strategy.name + ". List of supported versions: " + + frameworkStrategies.stream() + .map(p -> p.name) + .collect(Collectors.joining(", "))); + } + } + this.targetFramework = strategies.stream().map(p -> p.name) + .collect(Collectors.joining(";")); + LOGGER.info("Generating code for .NET Framework {}", this.targetFramework); + } + + public void setTestTargetFramework(String testTargetFramework) { + this.testTargetFramework = testTargetFramework; + } + + public void setTestTargetFramework(List strategies) { + this.testTargetFramework = strategies.stream().map(p -> p.testTargetFramework) + .collect(Collectors.joining(";")); + } + + public void setTargetFrameworkNuget(String targetFrameworkNuget) { + this.targetFrameworkNuget = targetFrameworkNuget; + } + + public void setTargetFrameworkNuget(List strategies) { + this.targetFrameworkNuget = strategies.stream().map(p -> p.getNugetFrameworkIdentifier()) + .collect(Collectors.joining(";")); + } + + public void setValidatable(boolean validatable) { + this.validatable = validatable; + } + + public void setCaseInsensitiveResponseHeaders(final Boolean caseInsensitiveResponseHeaders) { + this.caseInsensitiveResponseHeaders = caseInsensitiveResponseHeaders; + } + + public void setLicenseId(String licenseId) { + this.licenseId = licenseId; + } + + @Override + public void setReleaseNote(String releaseNote) { + this.releaseNote = releaseNote; + } + + public void setPackageTags(String packageTags) { + this.packageTags = packageTags; + } + + public void setUseOneOfDiscriminatorLookup(boolean useOneOfDiscriminatorLookup) { + this.useOneOfDiscriminatorLookup = useOneOfDiscriminatorLookup; + } + + public boolean getUseOneOfDiscriminatorLookup() { + return this.useOneOfDiscriminatorLookup; + } + + @Override + public String toEnumVarName(String value, String datatype) { + if (value.length() == 0) { + return "Empty"; + } + + // for symbol, e.g. $, # + if (getSymbolName(value) != null) { + return camelize(getSymbolName(value)); + } + + // number + if (datatype.startsWith("int") || datatype.startsWith("long") || + datatype.startsWith("double") || datatype.startsWith("float")) { + String varName = "NUMBER_" + value; + varName = varName.replaceAll("-", "MINUS_"); + varName = varName.replaceAll("\\+", "PLUS_"); + varName = varName.replaceAll("\\.", "_DOT_"); + return varName; + } + + // string + String var = value.replaceAll(" ", "_"); + var = camelize(var); + var = var.replaceAll("\\W+", ""); + + if (var.matches("\\d.*")) { + return "_" + var; + } else { + return var; + } + } + + @Override + public String toModelDocFilename(String name) { + return toModelFilename(name); + } + + @Override + public String toVarName(String name) { + // sanitize name + name = sanitizeName(name); + + // if it's all upper case, do nothing + if (name.matches("^[A-Z_]*$")) { + return name; + } + + name = getNameUsingModelPropertyNaming(name); + + // for reserved word or word starting with number, append _ + if (isReservedWord(name) || name.matches("^\\d.*")) { + name = escapeReservedWord(name); + } + + // for function names in the model, escape with the "Property" prefix + if (propertySpecialKeywords.contains(name)) { + return camelize("property_" + name); + } + + return name; + } + + private CodegenModel reconcileInlineEnums(CodegenModel codegenModel, CodegenModel parentCodegenModel) { + // This generator uses inline classes to define enums, which breaks when + // dealing with models that have subTypes. To clean this up, we will analyze + // the parent and child models, look for enums that match, and remove + // them from the child models and leave them in the parent. + // Because the child models extend the parents, the enums will be available via the parent. + + // Only bother with reconciliation if the parent model has enums. + if (parentCodegenModel.hasEnums) { + + // Get the properties for the parent and child models + final List parentModelCodegenProperties = parentCodegenModel.vars; + List codegenProperties = codegenModel.vars; + + // Iterate over all of the parent model properties + boolean removedChildEnum = false; + for (CodegenProperty parentModelCodegenProperty : parentModelCodegenProperties) { + // Look for enums + if (parentModelCodegenProperty.isEnum) { + // Now that we have found an enum in the parent class, + // and search the child class for the same enum. + Iterator iterator = codegenProperties.iterator(); + while (iterator.hasNext()) { + CodegenProperty codegenProperty = iterator.next(); + if (codegenProperty.isEnum && codegenProperty.equals(parentModelCodegenProperty)) { + // We found an enum in the child class that is + // a duplicate of the one in the parent, so remove it. + iterator.remove(); + removedChildEnum = true; + } + } + } + } + + if (removedChildEnum) { + codegenModel.vars = codegenProperties; + } + } + + return codegenModel; + } + + private void syncBooleanProperty(final Map additionalProperties, final String key, final Consumer setter, final Boolean defaultValue) { + if (additionalProperties.containsKey(key)) { + setter.accept(convertPropertyToBooleanAndWriteBack(key)); + } else { + additionalProperties.put(key, defaultValue); + setter.accept(defaultValue); + } + } + + private void syncStringProperty(final Map additionalProperties, final String key, final Consumer setter, final String defaultValue) { + if (additionalProperties.containsKey(key)) { + setter.accept((String) additionalProperties.get(key)); + } else { + additionalProperties.put(key, defaultValue); + setter.accept(defaultValue); + } + } + + // https://docs.microsoft.com/en-us/dotnet/standard/net-standard + @SuppressWarnings("Duplicates") + private static abstract class FrameworkStrategy { + + private final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); + + static FrameworkStrategy NETSTANDARD_1_3 = new FrameworkStrategy("netstandard1.3", ".NET Standard 1.3 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_1_4 = new FrameworkStrategy("netstandard1.4", ".NET Standard 1.4 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_1_5 = new FrameworkStrategy("netstandard1.5", ".NET Standard 1.5 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_1_6 = new FrameworkStrategy("netstandard1.6", ".NET Standard 1.6 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_2_0 = new FrameworkStrategy("netstandard2.0", ".NET Standard 2.0 compatible", "netcoreapp2.0") { + }; + static FrameworkStrategy NETSTANDARD_2_1 = new FrameworkStrategy("netstandard2.1", ".NET Standard 2.1 compatible", "netcoreapp3.0") { + }; + static FrameworkStrategy NETCOREAPP_2_0 = new FrameworkStrategy("netcoreapp2.0", ".NET Core 2.0 compatible", "netcoreapp2.0", Boolean.FALSE) { + }; + static FrameworkStrategy NETCOREAPP_2_1 = new FrameworkStrategy("netcoreapp2.1", ".NET Core 2.1 compatible", "netcoreapp2.1", Boolean.FALSE) { + }; + static FrameworkStrategy NETCOREAPP_3_0 = new FrameworkStrategy("netcoreapp3.0", ".NET Core 3.0 compatible", "netcoreapp3.0", Boolean.FALSE) { + }; + static FrameworkStrategy NETCOREAPP_3_1 = new FrameworkStrategy("netcoreapp3.1", ".NET Core 3.1 compatible", "netcoreapp3.1", Boolean.FALSE) { + }; + static FrameworkStrategy NETFRAMEWORK_4_7 = new FrameworkStrategy("net47", ".NET Framework 4.7 compatible", "net47", Boolean.FALSE) { + }; + static FrameworkStrategy NET_5_0 = new FrameworkStrategy("net5.0", ".NET 5.0 compatible", "net5.0", Boolean.FALSE) { + }; + protected String name; + protected String description; + protected String testTargetFramework; + private Boolean isNetStandard = Boolean.TRUE; + + FrameworkStrategy(String name, String description, String testTargetFramework) { + this.name = name; + this.description = description; + this.testTargetFramework = testTargetFramework; + } + + FrameworkStrategy(String name, String description, String testTargetFramework, Boolean isNetStandard) { + this.name = name; + this.description = description; + this.testTargetFramework = testTargetFramework; + this.isNetStandard = isNetStandard; + } + + protected void configureAdditionalProperties(final Map properties) { + properties.putIfAbsent(CodegenConstants.DOTNET_FRAMEWORK, this.name); + + // not intended to be user-settable + properties.put(TARGET_FRAMEWORK_IDENTIFIER, this.getTargetFrameworkIdentifier()); + properties.put(TARGET_FRAMEWORK_VERSION, this.getTargetFrameworkVersion()); + properties.putIfAbsent(MCS_NET_VERSION_KEY, "4.6-api"); + + properties.put(NET_STANDARD, this.isNetStandard); + if (properties.containsKey(SUPPORTS_UWP)) { + LOGGER.warn(".NET {} generator does not support the UWP option. Use the csharp generator instead.", + this.name); + properties.remove(SUPPORTS_UWP); + } + } + + protected String getNugetFrameworkIdentifier() { + return this.name.toLowerCase(Locale.ROOT); + } + + protected String getTargetFrameworkIdentifier() { + if (this.isNetStandard) return ".NETStandard"; + else return ".NETCoreApp"; + } + + protected String getTargetFrameworkVersion() { + if (this.isNetStandard) return "v" + this.name.replace("netstandard", ""); + else return "v" + this.name.replace("netcoreapp", ""); + } + } + + protected void configureAdditionalPropertiesForFrameworks(final Map properties, List strategies) { + properties.putIfAbsent(CodegenConstants.DOTNET_FRAMEWORK, strategies.stream() + .map(p -> p.name) + .collect(Collectors.joining(";"))); + + // not intended to be user-settable + properties.put(TARGET_FRAMEWORK_IDENTIFIER, strategies.stream() + .map(p -> p.getTargetFrameworkIdentifier()) + .collect(Collectors.joining(";"))); + properties.put(TARGET_FRAMEWORK_VERSION, strategies.stream() + .map(p -> p.getTargetFrameworkVersion()) + .collect(Collectors.joining(";"))); + properties.putIfAbsent(MCS_NET_VERSION_KEY, "4.6-api"); + + properties.put(NET_STANDARD, strategies.stream().anyMatch(p -> Boolean.TRUE.equals(p.isNetStandard))); + } + + /** + * Return the instantiation type of the property, especially for map and array + * + * @param schema property schema + * @return string presentation of the instantiation type of the property + */ + @Override + public String toInstantiationType(Schema schema) { + if (ModelUtils.isMapSchema(schema)) { + Schema additionalProperties = getAdditionalProperties(schema); + String inner = getSchemaType(additionalProperties); + if (ModelUtils.isMapSchema(additionalProperties)) { + inner = toInstantiationType(additionalProperties); + } + return instantiationTypes.get("map") + ""; + } else if (ModelUtils.isArraySchema(schema)) { + ArraySchema arraySchema = (ArraySchema) schema; + String inner = getSchemaType(arraySchema.getItems()); + return instantiationTypes.get("array") + "<" + inner + ">"; + } else { + return null; + } + } + + @SuppressWarnings("unchecked") + @Override + public Map postProcessModels(Map objs) { + objs = super.postProcessModels(objs); + List models = (List) objs.get("models"); + + // add implements for serializable/parcelable to all models + for (Object _mo : models) { + Map mo = (Map) _mo; + CodegenModel cm = (CodegenModel) mo.get("model"); + + if (cm.oneOf != null && !cm.oneOf.isEmpty() && cm.oneOf.contains("ModelNull")) { + // if oneOf contains "null" type + cm.isNullable = true; + cm.oneOf.remove("ModelNull"); + } + + if (cm.anyOf != null && !cm.anyOf.isEmpty() && cm.anyOf.contains("ModelNull")) { + // if anyOf contains "null" type + cm.isNullable = true; + cm.anyOf.remove("ModelNull"); + } + } + + return objs; + } + + @Override + public void postProcess() { + System.out.println("################################################################################"); + System.out.println("# Thanks for using OpenAPI Generator. #"); + System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); + System.out.println("# https://opencollective.com/openapi_generator/donate #"); + System.out.println("# #"); + System.out.println("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#"); + System.out.println("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #"); + System.out.println("################################################################################"); + } + + @Override + protected void updateModelForObject(CodegenModel m, Schema schema) { + /** + * we have a custom version of this function so we only set isMap to true if + * ModelUtils.isMapSchema + * In other generators, isMap is true for all type object schemas + */ + if (schema.getProperties() != null || schema.getRequired() != null && !(schema instanceof ComposedSchema)) { + // passing null to allProperties and allRequired as there's no parent + addVars(m, unaliasPropertySchema(schema.getProperties()), schema.getRequired(), null, null); + } + if (ModelUtils.isMapSchema(schema)) { + // an object or anyType composed schema that has additionalProperties set + addAdditionPropertiesToCodeGenModel(m, schema); + } else { + m.setIsMap(false); + if (ModelUtils.isFreeFormObject(openAPI, schema)) { + // non-composed object type with no properties + additionalProperties + // additionalProperties must be null, ObjectSchema, or empty Schema + addAdditionPropertiesToCodeGenModel(m, schema); + } + } + // process 'additionalProperties' + setAddProps(schema, m); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java new file mode 100644 index 00000000000..fb99c5a149a --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java @@ -0,0 +1,82 @@ +package org.openapitools.codegen.languages; + +import org.openapitools.codegen.*; +import io.swagger.models.properties.ArrayProperty; +import io.swagger.models.properties.MapProperty; +import io.swagger.models.properties.Property; +import io.swagger.models.parameters.Parameter; + +import java.io.File; +import java.util.*; + +import org.apache.commons.lang3.StringUtils; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedClientCodegen { + public static final String PROJECT_NAME = "projectName"; + + final Logger LOGGER = LoggerFactory.getLogger(CsharpNetcoreFunctionsServerCodegen.class); + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "csharp-netcore-functions"; + } + + public String getHelp() { + return "Generates a csharp server."; + } + + public CsharpNetcoreFunctionsServerCodegen() { + super(); + outputFolder = "generated-code" + File.separator + "csharp"; + modelTemplateFiles.put("model.mustache", ".cs"); + apiTemplateFiles.put("functions.mustache", ".cs"); + embeddedTemplateDir = templateDir = "csharp-netcore-functions"; + apiPackage = "Apis"; + modelPackage = "Models"; + String clientPackageDir = "generatedSrc/Client"; + supportingFiles.add(new SupportingFile("README.mustache", "generatedSrc", "README.md")); + supportingFiles.add(new SupportingFile("project.mustache", "generatedSrc", "project.json")); + + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", + clientPackageDir, "IApiAccessor.cs")); + supportingFiles.add(new SupportingFile("Configuration.mustache", + clientPackageDir, "Configuration.cs")); + supportingFiles.add(new SupportingFile("ApiClient.mustache", + clientPackageDir, "ApiClient.cs")); + supportingFiles.add(new SupportingFile("ApiException.mustache", + clientPackageDir, "ApiException.cs")); + supportingFiles.add(new SupportingFile("ApiResponse.mustache", + clientPackageDir, "ApiResponse.cs")); + supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", + clientPackageDir, "ExceptionFactory.cs")); + supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", + clientPackageDir, "OpenAPIDateConverter.cs")); + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + "generatedSrc" + File.separator + "Functions"; + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + "generatedSrc" + File.separator + "Models"; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + "/Docs").replace('/', File.separatorChar); + } + + @Override + public String apiTestFileFolder() { + return outputFolder + File.separator + "Tests" + File.separator + "Tests" + File.separator + apiPackage(); + } + +} diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index 78855ce50ad..727ec5d990f 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -23,6 +23,7 @@ org.openapitools.codegen.languages.CSharpClientCodegen org.openapitools.codegen.languages.CSharpNetCoreClientCodegen org.openapitools.codegen.languages.CSharpDotNet2ClientCodegen org.openapitools.codegen.languages.CSharpNancyFXServerCodegen +org.openapitools.codegen.languages.CsharpNetcoreFunctionsServerCodegen org.openapitools.codegen.languages.DartClientCodegen org.openapitools.codegen.languages.DartDioClientCodegen org.openapitools.codegen.languages.DartDioNextClientCodegen diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AbstractOpenAPISchema.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AbstractOpenAPISchema.mustache new file mode 100644 index 00000000000..05e78204959 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AbstractOpenAPISchema.mustache @@ -0,0 +1,68 @@ +{{>partial_header}} + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace {{packageName}}.{{modelPackage}} +{ + /// + /// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification + /// + {{>visibility}} abstract partial class AbstractOpenAPISchema + { + /// + /// Custom JSON serializer + /// + static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Error, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Custom JSON serializer for objects with additional properties + /// + static public readonly JsonSerializerSettings AdditionalPropertiesSerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Ignore, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Gets or Sets the actual instance + /// + public abstract Object ActualInstance { get; set; } + + /// + /// Gets or Sets IsNullable to indicate whether the instance is nullable + /// + public bool IsNullable { get; protected set; } + + /// + /// Gets or Sets the schema type, which can be either `oneOf` or `anyOf` + /// + public string SchemaType { get; protected set; } + + /// + /// Converts the instance into JSON string. + /// + public abstract string ToJson(); + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiClient.mustache new file mode 100644 index 00000000000..65cbf8d76bc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiClient.mustache @@ -0,0 +1,867 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +{{^netStandard}} +using System.Web; +{{/netStandard}} +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +using RestSharp; +using RestSharp.Deserializers; +using RestSharpMethod = RestSharp.Method; +{{#useWebRequest}} +using System.Net.Http; +{{/useWebRequest}} +{{#supportsRetry}} +using Polly; +{{/supportsRetry}} + +namespace {{packageName}}.Client +{ + /// + /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is {{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return (({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public T Deserialize(IRestResponse response) + { + var result = (T)Deserialize(response, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal object Deserialize(IRestResponse response, Type type) + { + if (type == typeof(byte[])) // return byte array + { + return response.RawBytes; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = response.RawBytes; + if (response.Headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in response.Headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(response.Content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + {{! NOTE: Any changes related to RestSharp should be done in this class. All other client classes are for extensibility by consumers.}} + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), + /// encapsulating general REST accessor use cases. + /// + {{>visibility}} partial class ApiClient : ISynchronousClient{{#supportsAsync}}, IAsynchronousClient{{/supportsAsync}} + { + private readonly string _baseUrl; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accomodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse response); + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + public ApiClient() + { + _baseUrl = {{packageName}}.Client.GlobalConfiguration.Instance.BasePath; + } + + /// + /// Initializes a new instance of the + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + _baseUrl = basePath; + } + + /// + /// Constructs the RestSharp version of an http method + /// + /// Swagger Client Custom HttpMethod + /// RestSharp's HttpMethod instance. + /// + private RestSharpMethod Method(HttpMethod method) + { + RestSharpMethod other; + switch (method) + { + case HttpMethod.Get: + other = RestSharpMethod.GET; + break; + case HttpMethod.Post: + other = RestSharpMethod.POST; + break; + case HttpMethod.Put: + other = RestSharpMethod.PUT; + break; + case HttpMethod.Delete: + other = RestSharpMethod.DELETE; + break; + case HttpMethod.Head: + other = RestSharpMethod.HEAD; + break; + case HttpMethod.Options: + other = RestSharpMethod.OPTIONS; + break; + case HttpMethod.Patch: + other = RestSharpMethod.PATCH; + break; + default: + throw new ArgumentOutOfRangeException("method", method, null); + } + + return other; + } + + /// + /// Provides all logic for constructing a new RestSharp . + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the RestSharp request. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new RestRequest instance. + /// + private RestRequest NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + RestRequest request = new RestRequest(Method(method)) + { + Resource = path, + JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) + }; + + if (options.PathParameters != null) + { + foreach (var pathParam in options.PathParameters) + { + request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); + } + } + + if (options.QueryParameters != null) + { + foreach (var queryParam in options.QueryParameters) + { + foreach (var value in queryParam.Value) + { + request.AddQueryParameter(queryParam.Key, value); + } + } + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.AddHeader(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + request.AddHeader(headerParam.Key, value); + } + } + } + + if (options.FormParameters != null) + { + foreach (var formParam in options.FormParameters) + { + request.AddParameter(formParam.Key, formParam.Value); + } + } + + if (options.Data != null) + { + if (options.Data is Stream stream) + { + var contentType = "application/octet-stream"; + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes[0]; + } + + var bytes = ClientUtils.ReadAsBytes(stream); + request.AddParameter(contentType, bytes, ParameterType.RequestBody); + } + else + { + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) + { + request.RequestFormat = DataFormat.Json; + } + else + { + // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. + } + } + else + { + // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. + request.RequestFormat = DataFormat.Json; + } + + request.AddJsonBody(options.Data); + } + } + + if (options.FileParameters != null) + { + foreach (var fileParam in options.FileParameters) + { + var bytes = ClientUtils.ReadAsBytes(fileParam.Value); + var fileStream = fileParam.Value as FileStream; + if (fileStream != null) + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + else + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + } + } + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + request.AddCookie(cookie.Name, cookie.Value); + } + } + + return request; + } + + private ApiResponse ToApiResponse(IRestResponse response) + { + T result = response.Data; + string rawContent = response.Content; + + var transformed = new ApiResponse(response.StatusCode, new Multimap({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, rawContent) + { + ErrorText = response.ErrorMessage, + Cookies = new List() + }; + + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.Cookies != null) + { + foreach (var responseCookies in response.Cookies) + { + transformed.Cookies.Add( + new Cookie( + responseCookies.Name, + responseCookies.Value, + responseCookies.Path, + responseCookies.Domain) + ); + } + } + + return transformed; + } + + private ApiResponse Exec(RestRequest req, IReadableConfiguration configuration) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = client.Execute(req); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + {{#supportsAsync}} + private async Task> ExecAsync(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + {{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + {{/supportsRetry}} + response = await client.ExecuteAsync(req, cancellationToken).ConfigureAwait(false); + {{#supportsRetry}} + } + {{/supportsRetry}} + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken); + } + #endregion IAsynchronousClient + {{/supportsAsync}} + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Patch, path, options, config), config); + } + #endregion ISynchronousClient + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiException.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiException.mustache new file mode 100644 index 00000000000..f7dadc5573c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiException.mustache @@ -0,0 +1,60 @@ +{{>partial_header}} + +using System; + +namespace {{packageName}}.Client +{ + /// + /// API Exception + /// + {{>visibility}} class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public object ErrorContent { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() { } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + /// HTTP Headers. + public ApiException(int errorCode, string message, object errorContent = null, Multimap headers = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + this.Headers = headers; + } + } + +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiResponse.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiResponse.mustache new file mode 100644 index 00000000000..161c2acd16c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ApiResponse.mustache @@ -0,0 +1,158 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// The content of this response + /// + Object Content { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + Multimap Headers { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + List Cookies { get; set; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + } + + /// + /// API Response + /// + public class ApiResponse : IApiResponse + { + #region Properties + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + public string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + public List Cookies { get; set; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The data type of + /// + public object Content + { + get { return Data; } + } + + /// + /// The raw content + /// + public string RawContent { get; } + + #endregion Properties + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data, string rawContent) + { + StatusCode = statusCode; + Headers = headers; + Data = data; + RawContent = rawContent; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data) : this(statusCode, headers, data, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null) + { + } + + #endregion Constructors + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AssemblyInfo.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AssemblyInfo.mustache new file mode 100644 index 00000000000..d5d937dc19f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/AssemblyInfo.mustache @@ -0,0 +1,40 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("{{packageTitle}}")] +[assembly: AssemblyDescription("{{packageDescription}}")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("{{packageCompany}}")] +[assembly: AssemblyProduct("{{packageProductName}}")] +[assembly: AssemblyCopyright("{{packageCopyright}}")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("{{packageVersion}}")] +[assembly: AssemblyFileVersion("{{packageVersion}}")] +{{^supportsAsync}} +// Settings which don't support asynchronous operations rely on non-public constructors +// This is due to how RestSharp requires the type constraint `where T : new()` in places it probably shouldn't. +[assembly: InternalsVisibleTo("RestSharp")] +[assembly: InternalsVisibleTo("NewtonSoft.Json")] +[assembly: InternalsVisibleTo("JsonSubTypes")] +{{/supportsAsync}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ClientUtils.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ClientUtils.mustache new file mode 100644 index 00000000000..3c04dcdbd0c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ClientUtils.mustache @@ -0,0 +1,239 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; +{{#useCompareNetObjects}} +using KellermanSoftware.CompareNetObjects; +{{/useCompareNetObjects}} + +namespace {{packageName}}.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + {{#useCompareNetObjects}} + /// + /// An instance of CompareLogic. + /// + public static CompareLogic compareLogic; + + /// + /// Static contstructor to initialise compareLogic. + /// + static ClientUtils() + { + compareLogic = new CompareLogic(); + } + + {{/useCompareNetObjects}} + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// Convert params to key/value pairs. + /// Use collectionFormat to properly format lists and collections. + /// + /// The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi + /// Key name. + /// Value object. + /// A multimap of keys with 1..n associated values. + public static Multimap ParameterToMultiMap(string collectionFormat, string name, object value) + { + var parameters = new Multimap(); + + if (value is ICollection collection && collectionFormat == "multi") + { + foreach (var item in collection) + { + parameters.Add(name, ParameterToString(item)); + } + } + else if (value is IDictionary dictionary) + { + if(collectionFormat == "deepObject") { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value)); + } + } + else { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value)); + } + } + } + else + { + parameters.Add(name, ParameterToString(value)); + } + + return parameters; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// An optional configuration instance, providing formatting options used in processing. + /// Formatted string. + public static string ParameterToString(object obj, IReadableConfiguration configuration = null) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) + return string.Join(",", collection.Cast()); + + return Convert.ToString(obj, CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// 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) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Configuration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Configuration.mustache new file mode 100644 index 00000000000..ead56414441 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Configuration.mustache @@ -0,0 +1,574 @@ +{{>partial_header}} + +using System; +{{^net35}} +using System.Collections.Concurrent; +{{/net35}} +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; + +namespace {{packageName}}.Client +{ + /// + /// Represents a set of configuration settings + /// + {{>visibility}} class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "{{packageVersion}}"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var status = (int)response.StatusCode; + if (status >= 400) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.RawContent), + response.RawContent, response.Headers); + } + {{^netStandard}} + if (status == 0) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.ErrorText), response.ErrorText); + } + {{/netStandard}} + return null; + }; + + #endregion Static Members + + #region Private Members + + /// + /// Defines the base path of the target API server. + /// Example: http://localhost:3000/v1/ + /// + private string _basePath; + + /// + /// Gets or sets the API key based on the authentication name. + /// This is the key and value comprising the "secret" for acessing an API. + /// + /// The API key. + private IDictionary _apiKey; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + {{#servers.0}} + + /// + /// Gets or sets the servers defined in the OpenAPI spec. + /// + /// The servers + private IList> _servers; + {{/servers.0}} + {{#hasHttpSignatureMethods}} + + /// + /// HttpSigning configuration + /// + private HttpSigningConfiguration _HttpSigningConfiguration = null; + {{/hasHttpSignatureMethods}} + #endregion Private Members + + #region Constructors + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration() + { + Proxy = null; + UserAgent = "{{#httpUserAgent}}{{.}}{{/httpUserAgent}}{{^httpUserAgent}}OpenAPI-Generator/{{packageVersion}}/csharp{{/httpUserAgent}}"; + BasePath = "{{{basePath}}}"; + DefaultHeaders = new {{^net35}}Concurrent{{/net35}}Dictionary(); + ApiKey = new {{^net35}}Concurrent{{/net35}}Dictionary(); + ApiKeyPrefix = new {{^net35}}Concurrent{{/net35}}Dictionary(); + {{#servers}} + {{#-first}} + Servers = new List>() + { + {{/-first}} + { + new Dictionary { + {"url", "{{{url}}}"}, + {"description", "{{{description}}}{{^description}}No description provided{{/description}}"}, + {{#variables}} + {{#-first}} + { + "variables", new Dictionary { + {{/-first}} + { + "{{{name}}}", new Dictionary { + {"description", "{{{description}}}{{^description}}No description provided{{/description}}"}, + {"default_value", "{{{defaultValue}}}"}, + {{#enumValues}} + {{#-first}} + { + "enum_values", new List() { + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + } + } + {{/-last}} + {{/enumValues}} + } + }{{^-last}},{{/-last}} + {{#-last}} + } + } + {{/-last}} + {{/variables}} + } + }{{^-last}},{{/-last}} + {{#-last}} + }; + {{/-last}} + {{/servers}} + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration( + IDictionary defaultHeaders, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "{{{basePath}}}") : this() + { + if (string.{{^net35}}IsNullOrWhiteSpace{{/net35}}{{#net35}}IsNullOrEmpty{{/net35}}(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeaders == null) + throw new ArgumentNullException("defaultHeaders"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeaders) + { + DefaultHeaders.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + #endregion Constructors + + #region Properties + + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath { + get { return _basePath; } + set { _basePath = value; } + } + + /// + /// Gets or sets the default header. + /// + [Obsolete("Use DefaultHeaders instead.")] + public virtual IDictionary DefaultHeader + { + get + { + return DefaultHeaders; + } + set + { + DefaultHeaders = value; + } + } + + /// + /// Gets or sets the default headers. + /// + public virtual IDictionary DefaultHeaders { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout { get; set; } + + /// + /// Gets or sets the proxy + /// + /// Proxy. + public virtual WebProxy Proxy { get; set; } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + string apiKeyValue; + ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); + string apiKeyPrefix; + if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) + { + return apiKeyPrefix + " " + apiKeyValue; + } + + return apiKeyValue; + } + + /// + /// Gets or sets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + public X509CertificateCollection ClientCertificates { get; set; } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// This helper property simplifies code generation. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + _tempFolderPath = Path.GetTempPath(); + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + { + _tempFolderPath = value; + } + else + { + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + } + + /// + /// Gets or sets the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// Whatever you set here will be prepended to the value defined in AddApiKey. + /// + /// An example invocation here might be: + /// + /// ApiKeyPrefix["Authorization"] = "Bearer"; + /// + /// … where ApiKey["Authorization"] would then be used to set the value of your bearer token. + /// + /// + /// OAuth2 workflows should set tokens via AccessToken. + /// + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + {{#servers.0}} + + /// + /// Gets or sets the servers. + /// + /// The servers. + public virtual IList> Servers + { + get { return _servers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Servers may not be null."); + } + _servers = value; + } + } + + /// + /// Returns URL based on server settings without providing values + /// for the variables + /// + /// Array index of the server settings. + /// The server URL. + public string GetServerUrl(int index) + { + return GetServerUrl(index, null); + } + + /// + /// Returns URL based on server settings. + /// + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + public string GetServerUrl(int index, Dictionary inputVariables) + { + if (index < 0 || index >= Servers.Count) + { + throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {Servers.Count}."); + } + + if (inputVariables == null) + { + inputVariables = new Dictionary(); + } + + IReadOnlyDictionary server = Servers[index]; + string url = (string)server["url"]; + + // go through variable and assign a value + foreach (KeyValuePair variable in (IReadOnlyDictionary)server["variables"]) + { + + IReadOnlyDictionary serverVariables = (IReadOnlyDictionary)(variable.Value); + + if (inputVariables.ContainsKey(variable.Key)) + { + if (((List)serverVariables["enum_values"]).Contains(inputVariables[variable.Key])) + { + url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]); + } + else + { + throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List)serverVariables["enum_values"]}"); + } + } + else + { + // use defualt value + url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]); + } + } + + return url; + } + {{/servers.0}} + {{#hasHttpSignatureMethods}} + + /// + /// Gets and Sets the HttpSigningConfiuration + /// + public HttpSigningConfiguration HttpSigningConfiguration + { + get { return _HttpSigningConfiguration; } + set { _HttpSigningConfiguration = value; } + } + {{/hasHttpSignatureMethods}} + + #endregion Properties + + #region Methods + + /// + /// Returns a string with essential information for debugging. + /// + public static string ToDebugReport() + { + string report = "C# SDK ({{{packageName}}}) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: {{{version}}}\n"; + report += " SDK Package Version: {{{packageVersion}}}\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + + #region Static Members + /// + /// Merge configurations. + /// + /// First configuration. + /// Second configuration. + /// Merged configuration. + public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second) + { + if (second == null) return first ?? GlobalConfiguration.Instance; + + Dictionary apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value; + foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value; + foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value; + + var config = new Configuration + { + ApiKey = apiKey, + ApiKeyPrefix = apiKeyPrefix, + DefaultHeaders = defaultHeaders, + BasePath = second.BasePath ?? first.BasePath, + Timeout = second.Timeout, + Proxy = second.Proxy ?? first.Proxy, + UserAgent = second.UserAgent ?? first.UserAgent, + Username = second.Username ?? first.Username, + Password = second.Password ?? first.Password, + AccessToken = second.AccessToken ?? first.AccessToken, + {{#hasHttpSignatureMethods}} + HttpSigningConfiguration = second.HttpSigningConfiguration ?? first.HttpSigningConfiguration, + {{/hasHttpSignatureMethods}} + TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, + DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat + }; + return config; + } + #endregion Static Members + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ExceptionFactory.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ExceptionFactory.mustache new file mode 100644 index 00000000000..4a141f6f1ae --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ExceptionFactory.mustache @@ -0,0 +1,14 @@ +{{>partial_header}} + +using System; + +namespace {{packageName}}.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + {{>visibility}} delegate Exception ExceptionFactory(string methodName, IApiResponse response); +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/GlobalConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/GlobalConfiguration.mustache new file mode 100644 index 00000000000..bdfa4b99cc1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/GlobalConfiguration.mustache @@ -0,0 +1,59 @@ +{{>partial_header}} + +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// provides a compile-time extension point for globally configuring + /// API Clients. + /// + /// + /// A customized implementation via partial class may reside in another file and may + /// be excluded from automatic generation via a .openapi-generator-ignore file. + /// + public partial class GlobalConfiguration : Configuration + { + #region Private Members + + private static readonly object GlobalConfigSync = new { }; + private static IReadableConfiguration _globalConfiguration; + + #endregion Private Members + + #region Constructors + + /// + private GlobalConfiguration() + { + } + + /// + public GlobalConfiguration(IDictionary defaultHeader, IDictionary apiKey, IDictionary apiKeyPrefix, string basePath = "http://localhost:3000/api") : base(defaultHeader, apiKey, apiKeyPrefix, basePath) + { + } + + static GlobalConfiguration() + { + Instance = new GlobalConfiguration(); + } + + #endregion Constructors + + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static IReadableConfiguration Instance + { + get { return _globalConfiguration; } + set + { + lock (GlobalConfigSync) + { + _globalConfiguration = value; + } + } + } + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpMethod.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpMethod.mustache new file mode 100644 index 00000000000..904a042a9ac --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpMethod.mustache @@ -0,0 +1,25 @@ +{{>partial_header}} + +namespace {{packageName}}.Client +{ + /// + /// Http methods supported by swagger + /// + public enum HttpMethod + { + /// HTTP GET request. + Get, + /// HTTP POST request. + Post, + /// HTTP PUT request. + Put, + /// HTTP DELETE request. + Delete, + /// HTTP HEAD request. + Head, + /// HTTP OPTIONS request. + Options, + /// HTTP PATCH request. + Patch + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpSigningConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpSigningConfiguration.mustache new file mode 100644 index 00000000000..cc8c275e40b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/HttpSigningConfiguration.mustache @@ -0,0 +1,757 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using System; +using System.Collections.Generic; +using System.IO; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; +using System.Text; +using System.Web; + +namespace {{packageName}}.Client +{ + /// + /// Class for HttpSigning auth related parameter and methods + /// + public class HttpSigningConfiguration + { + #region + /// + /// Initailize the HashAlgorithm and SigningAlgorithm to default value + /// + public HttpSigningConfiguration() + { + HashAlgorithm = HashAlgorithmName.SHA256; + SigningAlgorithm = "PKCS1-v15"; + } + #endregion + + #region Properties + /// + ///Gets the Api keyId + /// + public string KeyId { get; set; } + + /// + /// Gets the Key file path + /// + public string KeyFilePath { get; set; } + + /// + /// Gets the key pass phrase for password protected key + /// + public SecureString KeyPassPhrase { get; set; } + + /// + /// Gets the HTTP signing header + /// + public List HttpSigningHeader { get; set; } + + /// + /// Gets the hash algorithm sha256 or sha512 + /// + public HashAlgorithmName HashAlgorithm { get; set; } + + /// + /// Gets the signing algorithm + /// + public string SigningAlgorithm { get; set; } + + /// + /// Gets the Signature validaty period in seconds + /// + public int SignatureValidityPeriod { get; set; } + + #endregion + + #region enum + private enum PrivateKeyType + { + None = 0, + RSA = 1, + ECDSA = 2, + } + #endregion + + #region Methods + /// + /// Gets the Headers for HttpSigning + /// + /// Base path + /// HTTP method + /// Path + /// Request options + /// + internal Dictionary GetHttpSignedHeader(string basePath,string method, string path, RequestOptions requestOptions) + { + const string HEADER_REQUEST_TARGET = "(request-target)"; + //The time when the HTTP signature expires. The API server should reject HTTP requests + //that have expired. + const string HEADER_EXPIRES = "(expires)"; + //The 'Date' header. + const string HEADER_DATE = "Date"; + //The 'Host' header. + const string HEADER_HOST = "Host"; + //The time when the HTTP signature was generated. + const string HEADER_CREATED = "(created)"; + //When the 'Digest' header is included in the HTTP signature, the client automatically + //computes the digest of the HTTP request body, per RFC 3230. + const string HEADER_DIGEST = "Digest"; + //The 'Authorization' header is automatically generated by the client. It includes + //the list of signed headers and a base64-encoded signature. + const string HEADER_AUTHORIZATION = "Authorization"; + + //Hash table to store singed headers + var HttpSignedRequestHeader = new Dictionary(); + var HttpSignatureHeader = new Dictionary(); + + if (HttpSigningHeader.Count == 0) + { + HttpSigningHeader.Add("(created)"); + } + + if (requestOptions.PathParameters != null) + { + foreach (var pathParam in requestOptions.PathParameters) + { + var tempPath = path.Replace(pathParam.Key, "0"); + path = string.Format(tempPath, pathParam.Value); + } + } + + var httpValues = HttpUtility.ParseQueryString(string.Empty); + foreach (var parameter in requestOptions.QueryParameters) + { +#if (NETCOREAPP) + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key) + "[]", value); + } + } + else + { + httpValues.Add(HttpUtility.UrlEncode(parameter.Key), parameter.Value[0]); + } +#else + if (parameter.Value.Count > 1) + { // array + foreach (var value in parameter.Value) + { + httpValues.Add(parameter.Key + "[]", value); + } + } + else + { + httpValues.Add(parameter.Key, parameter.Value[0]); + } +#endif + } + var uriBuilder = new UriBuilder(string.Concat(basePath, path)); + uriBuilder.Query = httpValues.ToString().Replace("+", "%20"); + + var dateTime = DateTime.Now; + string Digest = string.Empty; + + //get the body + string requestBody = string.Empty; + if (requestOptions.Data != null) + { + var serializerSettings = new JsonSerializerSettings(); + requestBody = JsonConvert.SerializeObject(requestOptions.Data, serializerSettings); + } + + if (HashAlgorithm == HashAlgorithmName.SHA256) + { + var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody); + Digest = string.Format("SHA-256={0}", Convert.ToBase64String(bodyDigest)); + } + else if (HashAlgorithm == HashAlgorithmName.SHA512) + { + var bodyDigest = GetStringHash(HashAlgorithm.ToString(), requestBody); + Digest = string.Format("SHA-512={0}", Convert.ToBase64String(bodyDigest)); + } + else + { + throw new Exception(string.Format("{0} not supported", HashAlgorithm)); + } + + + foreach (var header in HttpSigningHeader) + { + if (header.Equals(HEADER_REQUEST_TARGET)) + { + var targetUrl = string.Format("{0} {1}{2}", method.ToLower(), uriBuilder.Path, uriBuilder.Query); + HttpSignatureHeader.Add(header.ToLower(), targetUrl); + } + else if (header.Equals(HEADER_EXPIRES)) + { + var expireDateTime = dateTime.AddSeconds(SignatureValidityPeriod); + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(expireDateTime).ToString()); + } + else if (header.Equals(HEADER_DATE)) + { + var utcDateTime = dateTime.ToString("r").ToString(); + HttpSignatureHeader.Add(header.ToLower(), utcDateTime); + HttpSignedRequestHeader.Add(HEADER_DATE, utcDateTime); + } + else if (header.Equals(HEADER_HOST)) + { + HttpSignatureHeader.Add(header.ToLower(), uriBuilder.Host); + HttpSignedRequestHeader.Add(HEADER_HOST, uriBuilder.Host); + } + else if (header.Equals(HEADER_CREATED)) + { + HttpSignatureHeader.Add(header.ToLower(), GetUnixTime(dateTime).ToString()); + } + else if (header.Equals(HEADER_DIGEST)) + { + HttpSignedRequestHeader.Add(HEADER_DIGEST, Digest); + HttpSignatureHeader.Add(header.ToLower(), Digest); + } + else + { + bool isHeaderFound = false; + foreach (var item in requestOptions.HeaderParameters) + { + if (string.Equals(item.Key, header, StringComparison.OrdinalIgnoreCase)) + { + HttpSignatureHeader.Add(header.ToLower(), item.Value.ToString()); + isHeaderFound = true; + break; + } + } + if (!isHeaderFound) + { + throw new Exception(string.Format("Cannot sign HTTP request.Request does not contain the {0} header.",header)); + } + } + + } + var headersKeysString = string.Join(" ", HttpSignatureHeader.Keys); + var headerValuesList = new List(); + + foreach (var keyVal in HttpSignatureHeader) + { + headerValuesList.Add(string.Format("{0}: {1}", keyVal.Key, keyVal.Value)); + + } + //Concatinate headers value separated by new line + var headerValuesString = string.Join("\n", headerValuesList); + var signatureStringHash = GetStringHash(HashAlgorithm.ToString(), headerValuesString); + string headerSignatureStr = null; + var keyType = GetKeyType(KeyFilePath); + + if (keyType == PrivateKeyType.RSA) + { + headerSignatureStr = GetRSASignature(signatureStringHash); + } + else if (keyType == PrivateKeyType.ECDSA) + { + headerSignatureStr = GetECDSASignature(signatureStringHash); + } + var cryptographicScheme = "hs2019"; + var authorizationHeaderValue = string.Format("Signature keyId=\"{0}\",algorithm=\"{1}\"", + KeyId, cryptographicScheme); + + if (HttpSignatureHeader.ContainsKey(HEADER_CREATED)) + { + authorizationHeaderValue += string.Format(",created={0}", HttpSignatureHeader[HEADER_CREATED]); + } + + if (HttpSignatureHeader.ContainsKey(HEADER_EXPIRES)) + { + authorizationHeaderValue += string.Format(",expires={0}", HttpSignatureHeader[HEADER_EXPIRES]); + } + + authorizationHeaderValue += string.Format(",headers=\"{0}\",signature=\"{1}\"", + headersKeysString, headerSignatureStr); + + HttpSignedRequestHeader.Add(HEADER_AUTHORIZATION, authorizationHeaderValue); + + return HttpSignedRequestHeader; + } + + private byte[] GetStringHash(string hashName, string stringToBeHashed) + { + var hashAlgorithm = System.Security.Cryptography.HashAlgorithm.Create(hashName); + var bytes = Encoding.UTF8.GetBytes(stringToBeHashed); + var stringHash = hashAlgorithm.ComputeHash(bytes); + return stringHash; + } + + private int GetUnixTime(DateTime date2) + { + DateTime date1 = new DateTime(1970, 01, 01); + TimeSpan timeSpan = date2 - date1; + return (int)timeSpan.TotalSeconds; + } + + private string GetRSASignature(byte[] stringToSign) + { + RSA rsa = GetRSAProviderFromPemFile(KeyFilePath, KeyPassPhrase); + if (SigningAlgorithm == "RSASSA-PSS") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pss); + return Convert.ToBase64String(signedbytes); + } + else if (SigningAlgorithm == "PKCS1-v15") + { + var signedbytes = rsa.SignHash(stringToSign, HashAlgorithm, RSASignaturePadding.Pkcs1); + return Convert.ToBase64String(signedbytes); + } + return string.Empty; + } + + /// + /// Gets the ECDSA signature + /// + /// + /// + private string GetECDSASignature(byte[] dataToSign) + { + if (!File.Exists(KeyFilePath)) + { + throw new Exception("key file path does not exist."); + } + + var ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; + var ecKeyFooter = "-----END EC PRIVATE KEY-----"; + var keyStr = File.ReadAllText(KeyFilePath); + var ecKeyBase64String = keyStr.Replace(ecKeyHeader, "").Replace(ecKeyFooter, "").Trim(); + var keyBytes = System.Convert.FromBase64String(ecKeyBase64String); + var ecdsa = ECDsa.Create(); + +#if (NETCOREAPP3_0 || NETCOREAPP3_1 || NET5_0) + var byteCount = 0; + if (KeyPassPhrase != null) + { + IntPtr unmanagedString = IntPtr.Zero; + try + { + // convert secure string to byte array + unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(KeyPassPhrase); + ecdsa.ImportEncryptedPkcs8PrivateKey(Encoding.UTF8.GetBytes(Marshal.PtrToStringUni(unmanagedString)), keyBytes, out byteCount); + } + finally + { + if (unmanagedString != IntPtr.Zero) + { + Marshal.ZeroFreeBSTR(unmanagedString); + } + } + } + else + { + ecdsa.ImportPkcs8PrivateKey(keyBytes, out byteCount); + } + var signedBytes = ecdsa.SignHash(dataToSign); + var derBytes = ConvertToECDSAANS1Format(signedBytes); + var signedString = System.Convert.ToBase64String(derBytes); + + return signedString; +#else + throw new Exception("ECDSA signing is supported only on NETCOREAPP3_0 and above"); +#endif + + } + + private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) + { + var derBytes = new List(); + byte derLength = 68; //default lenght for ECDSA code signinged bit 0x44 + byte rbytesLength = 32; //R length 0x20 + byte sbytesLength = 32; //S length 0x20 + var rBytes = new List(); + var sBytes = new List(); + for (int i = 0; i < 32; i++) + { + rBytes.Add(signedBytes[i]); + } + for (int i = 32; i < 64; i++) + { + sBytes.Add(signedBytes[i]); + } + + if (rBytes[0] > 0x7F) + { + derLength++; + rbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(rBytes); + rBytes.Clear(); + rBytes.Add(0x00); + rBytes.AddRange(tempBytes); + } + + if (sBytes[0] > 0x7F) + { + derLength++; + sbytesLength++; + var tempBytes = new List(); + tempBytes.AddRange(sBytes); + sBytes.Clear(); + sBytes.Add(0x00); + sBytes.AddRange(tempBytes); + + } + + derBytes.Add(48); //start of the sequence 0x30 + derBytes.Add(derLength); //total length r lenth, type and r bytes + + derBytes.Add(2); //tag for integer + derBytes.Add(rbytesLength); //length of r + derBytes.AddRange(rBytes); + + derBytes.Add(2); //tag for integer + derBytes.Add(sbytesLength); //length of s + derBytes.AddRange(sBytes); + return derBytes.ToArray(); + } + + private RSACryptoServiceProvider GetRSAProviderFromPemFile(string pemfile, SecureString keyPassPharse = null) + { + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; + const string pempubfooter = "-----END PUBLIC KEY-----"; + bool isPrivateKeyFile = true; + byte[] pemkey = null; + + if (!File.Exists(pemfile)) + { + throw new Exception("private key file does not exist."); + } + string pemstr = File.ReadAllText(pemfile).Trim(); + + if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) + { + isPrivateKeyFile = false; + } + + if (isPrivateKeyFile) + { + pemkey = ConvertPrivateKeyToBytes(pemstr, keyPassPharse); + if (pemkey == null) + { + return null; + } + return DecodeRSAPrivateKey(pemkey); + } + return null; + } + + private byte[] ConvertPrivateKeyToBytes(string instr, SecureString keyPassPharse = null) + { + const string pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; + const string pemprivfooter = "-----END RSA PRIVATE KEY-----"; + string pemstr = instr.Trim(); + byte[] binkey; + + if (!pemstr.StartsWith(pemprivheader) || !pemstr.EndsWith(pemprivfooter)) + { + return null; + } + + StringBuilder sb = new StringBuilder(pemstr); + sb.Replace(pemprivheader, ""); + sb.Replace(pemprivfooter, ""); + string pvkstr = sb.ToString().Trim(); + + try + { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key + binkey = Convert.FromBase64String(pvkstr); + return binkey; + } + catch (System.FormatException) + { + StringReader str = new StringReader(pvkstr); + + //-------- read PEM encryption info. lines and extract salt ----- + if (!str.ReadLine().StartsWith("Proc-Type: 4,ENCRYPTED")) + { + return null; + } + string saltline = str.ReadLine(); + if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) + { + return null; + } + string saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + byte[] salt = new byte[saltstr.Length / 2]; + for (int i = 0; i < salt.Length; i++) + salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); + if (!(str.ReadLine() == "")) + { + return null; + } + + //------ remaining b64 data is encrypted RSA key ---- + string encryptedstr = str.ReadToEnd(); + + try + { //should have b64 encrypted RSA key now + binkey = Convert.FromBase64String(encryptedstr); + } + catch (System.FormatException) + { //data is not in base64 fromat + return null; + } + + byte[] deskey = GetEncryptedKey(salt, keyPassPharse, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes + if (deskey == null) + { + return null; + } + + //------ Decrypt the encrypted 3des-encrypted RSA private key ------ + byte[] rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV + return rsakey; + } + } + + private RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) + { + byte[] MODULUS, E, D, P, Q, DP, DQ, IQ; + + // --------- Set up stream to decode the asn.1 encoded RSA private key ------ + MemoryStream mem = new MemoryStream(privkey); + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + int elems = 0; + try + { + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + { + binr.ReadByte(); //advance 1 byte + } + else if (twobytes == 0x8230) + { + binr.ReadInt16(); //advance 2 bytes + } + else + { + return null; + } + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) //version number + { + return null; + } + bt = binr.ReadByte(); + if (bt != 0x00) + { + return null; + } + + //------ all private key components are Integer sequences ---- + elems = GetIntegerSize(binr); + MODULUS = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + E = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + D = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + P = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + Q = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + DQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + IQ = binr.ReadBytes(elems); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); + RSAParameters RSAparams = new RSAParameters(); + RSAparams.Modulus = MODULUS; + RSAparams.Exponent = E; + RSAparams.D = D; + RSAparams.P = P; + RSAparams.Q = Q; + RSAparams.DP = DP; + RSAparams.DQ = DQ; + RSAparams.InverseQ = IQ; + RSA.ImportParameters(RSAparams); + return RSA; + } + catch (Exception) + { + return null; + } + finally + { + binr.Close(); + } + } + + private int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + byte lowbyte = 0x00; + byte highbyte = 0x00; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) //expect integer + { + return 0; + } + bt = binr.ReadByte(); + + if (bt == 0x81) + { + count = binr.ReadByte(); // data size in next byte + } + else if (bt == 0x82) + { + highbyte = binr.ReadByte(); // data size in next 2 bytes + lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; // we already have the data size + } + while (binr.ReadByte() == 0x00) + { + //remove high order zeros in data + count -= 1; + } + binr.BaseStream.Seek(-1, SeekOrigin.Current); + //last ReadByte wasn't a removed zero, so back up a byte + return count; + } + + private byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) + { + IntPtr unmanagedPswd = IntPtr.Zero; + int HASHLENGTH = 16; //MD5 bytes + byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store contatenated Mi hashed results + + byte[] psbytes = new byte[secpswd.Length]; + unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); + Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); + Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); + + // --- contatenate salt and pswd bytes into fixed data array --- + byte[] data00 = new byte[psbytes.Length + salt.Length]; + Array.Copy(psbytes, data00, psbytes.Length); //copy the pswd bytes + Array.Copy(salt, 0, data00, psbytes.Length, salt.Length); //concatenate the salt bytes + + // ---- do multi-hashing and contatenate results D1, D2 ... into keymaterial bytes ---- + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] result = null; + byte[] hashtarget = new byte[HASHLENGTH + data00.Length]; //fixed length initial hashtarget + + for (int j = 0; j < miter; j++) + { + // ---- Now hash consecutively for count times ------ + if (j == 0) + { + result = data00; //initialize + } + else + { + Array.Copy(result, hashtarget, result.Length); + Array.Copy(data00, 0, hashtarget, result.Length, data00.Length); + result = hashtarget; + } + + for (int i = 0; i < count; i++) + result = md5.ComputeHash(result); + Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //contatenate to keymaterial + } + byte[] deskey = new byte[24]; + Array.Copy(keymaterial, deskey, deskey.Length); + + Array.Clear(psbytes, 0, psbytes.Length); + Array.Clear(data00, 0, data00.Length); + Array.Clear(result, 0, result.Length); + Array.Clear(hashtarget, 0, hashtarget.Length); + Array.Clear(keymaterial, 0, keymaterial.Length); + return deskey; + } + + private byte[] DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) + { + MemoryStream memst = new MemoryStream(); + TripleDES alg = TripleDES.Create(); + alg.Key = desKey; + alg.IV = IV; + try + { + CryptoStream cs = new CryptoStream(memst, alg.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(cipherData, 0, cipherData.Length); + cs.Close(); + } + catch (Exception) + { + return null; + } + byte[] decryptedData = memst.ToArray(); + return decryptedData; + } + + /// + /// Detect the key type from the pem file. + /// + /// key file path in pem format + /// + private PrivateKeyType GetKeyType(string keyFilePath) + { + if (!File.Exists(keyFilePath)) + { + throw new Exception("Key file path does not exist."); + } + + var ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY"; + var ecPrivateKeyFooter = "END EC PRIVATE KEY"; + var rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY"; + var rsaPrivateFooter = "END RSA PRIVATE KEY"; + //var pkcs8Header = "BEGIN PRIVATE KEY"; + //var pkcs8Footer = "END PRIVATE KEY"; + var keyType = PrivateKeyType.None; + var key = File.ReadAllLines(keyFilePath); + + if (key[0].ToString().Contains(rsaPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(rsaPrivateFooter)) + { + keyType = PrivateKeyType.RSA; + } + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + { + keyType = PrivateKeyType.ECDSA; + } + else if (key[0].ToString().Contains(ecPrivateKeyHeader) && + key[key.Length - 1].ToString().Contains(ecPrivateKeyFooter)) + { + + /* this type of key can hold many type different types of private key, but here due lack of pem header + Considering this as EC key + */ + //TODO :- update the key based on oid + keyType = PrivateKeyType.ECDSA; + } + else + { + throw new Exception("Either the key is invalid or key is not supported"); + + } + return keyType; + } + #endregion + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IApiAccessor.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IApiAccessor.mustache new file mode 100644 index 00000000000..a269f56e904 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IApiAccessor.mustache @@ -0,0 +1,29 @@ +{{>partial_header}} + +using System; + +namespace {{packageName}}.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + {{>visibility}} interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + IReadableConfiguration Configuration { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + string GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IAsynchronousClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IAsynchronousClient.mustache new file mode 100644 index 00000000000..f0c88fae473 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IAsynchronousClient.mustache @@ -0,0 +1,92 @@ +{{>partial_header}} + +using System; +using System.Threading.Tasks; + +namespace {{packageName}}.Client +{ + /// + /// Contract for Asynchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface IAsynchronousClient + { + /// + /// Executes a non-blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IReadableConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IReadableConfiguration.mustache new file mode 100644 index 00000000000..7c6487d92f8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/IReadableConfiguration.mustache @@ -0,0 +1,114 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Net; +using System.Security.Cryptography.X509Certificates; + +namespace {{packageName}}.Client +{ + /// + /// Represents a readable-only configuration contract. + /// + public interface IReadableConfiguration + { + /// + /// Gets the access token. + /// + /// Access token. + string AccessToken { get; } + + /// + /// Gets the API key. + /// + /// API key. + IDictionary ApiKey { get; } + + /// + /// Gets the API key prefix. + /// + /// API key prefix. + IDictionary ApiKeyPrefix { get; } + + /// + /// Gets the base path. + /// + /// Base path. + string BasePath { get; } + + /// + /// Gets the date time format. + /// + /// Date time foramt. + string DateTimeFormat { get; } + + /// + /// Gets the default header. + /// + /// Default header. + [Obsolete("Use DefaultHeaders instead.")] + IDictionary DefaultHeader { get; } + + /// + /// Gets the default headers. + /// + /// Default headers. + IDictionary DefaultHeaders { get; } + + /// + /// Gets the temp folder path. + /// + /// Temp folder path. + string TempFolderPath { get; } + + /// + /// Gets the HTTP connection timeout (in milliseconds) + /// + /// HTTP connection timeout. + int Timeout { get; } + + /// + /// Gets the proxy. + /// + /// Proxy. + WebProxy Proxy { get; } + + /// + /// Gets the user agent. + /// + /// User agent. + string UserAgent { get; } + + /// + /// Gets the username. + /// + /// Username. + string Username { get; } + + /// + /// Gets the password. + /// + /// Password. + string Password { get; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + + /// + /// Gets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + X509CertificateCollection ClientCertificates { get; } + {{#hasHttpSignatureMethods}} + + /// + /// Gets the HttpSigning configuration + /// + HttpSigningConfiguration HttpSigningConfiguration { get; } + {{/hasHttpSignatureMethods}} + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ISynchronousClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ISynchronousClient.mustache new file mode 100644 index 00000000000..c09bfbfed66 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ISynchronousClient.mustache @@ -0,0 +1,85 @@ +{{>partial_header}} + +using System; +using System.IO; + +namespace {{packageName}}.Client +{ + /// + /// Contract for Synchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface ISynchronousClient + { + /// + /// Executes a blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/JsonSubTypesTests.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/JsonSubTypesTests.mustache new file mode 100644 index 00000000000..9b1f66624d7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/JsonSubTypesTests.mustache @@ -0,0 +1,125 @@ +{{>partial_header}} + +using System.Collections.Generic; +using System.Linq; +using JsonSubTypes; +using Newtonsoft.Json; +using NUnit.Framework; + +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.{{modelPackage}}; +using {{packageName}}.Client; + +namespace {{packageName}}.Test.Client +{ + public class JsonSubTypesTests + { + [Test] + public void TestSimpleJsonSubTypesExample() + { + var annimal = + JsonConvert.DeserializeObject("{\"Kind\":\"Dog\",\"Breed\":\"Jack Russell Terrier\"}"); + Assert.AreEqual("Jack Russell Terrier", (annimal as Dog)?.Breed); + } + + [Test] + public void DeserializeObjectWithCustomMapping() + { + var annimal = + JsonConvert.DeserializeObject("{\"Sound\":\"Bark\",\"Breed\":\"Jack Russell Terrier\"}"); + Assert.AreEqual("Jack Russell Terrier", (annimal as Dog2)?.Breed); + } + + [Test] + public void DeserializeObjectMappingByPropertyPresence() + { + string json = + "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," + + "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," + + "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]"; + + + var persons = JsonConvert.DeserializeObject>(json); + Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill); + } + } + + [JsonConverter(typeof(JsonSubtypes), "Kind")] + public interface IAnimal + { + string Kind { get; } + } + + public class Dog : IAnimal + { + public Dog() + { + Kind = "Dog"; + } + + public string Kind { get; } + public string Breed { get; set; } + } + + class Cat : IAnimal + { + public Cat() + { + Kind = "Cat"; + } + + public string Kind { get; } + bool Declawed { get; set; } + } + + [JsonConverter(typeof(JsonSubtypes), "Sound")] + [JsonSubtypes.KnownSubType(typeof(Dog2), "Bark")] + [JsonSubtypes.KnownSubType(typeof(Cat2), "Meow")] + public class Animal2 + { + public virtual string Sound { get; } + public string Color { get; set; } + } + + public class Dog2 : Animal2 + { + public Dog2() + { + Sound = "Bark"; + } + + public override string Sound { get; } + public string Breed { get; set; } + } + + public class Cat2 : Animal2 + { + public Cat2() + { + Sound = "Meow"; + } + + public override string Sound { get; } + public bool Declawed { get; set; } + } + + [JsonConverter(typeof(JsonSubtypes))] + [JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")] + [JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")] + public class Person + { + public string FirstName { get; set; } + public string LastName { get; set; } + } + + public class Employee : Person + { + public string Department { get; set; } + public string JobTitle { get; set; } + } + + public class Artist : Person + { + public string Skill { get; set; } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Multimap.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Multimap.mustache new file mode 100644 index 00000000000..8624af00924 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Multimap.mustache @@ -0,0 +1,287 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// A dictionary in which one key has many associated values. + /// + /// The type of the key + /// The type of the value associated with the key. + public class Multimap : IDictionary> + { + #region Private Fields + + private readonly Dictionary> _dictionary; + + #endregion Private Fields + + #region Constructors + + /// + /// Empty Constructor. + /// + public Multimap() + { + _dictionary = new Dictionary>(); + } + + /// + /// Constructor with comparer. + /// + /// + public Multimap(IEqualityComparer comparer) + { + _dictionary = new Dictionary>(comparer); + } + + #endregion Constructors + + #region Enumerators + + /// + /// To get the enumerator. + /// + /// Enumerator + public IEnumerator>> GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + /// + /// To get the enumerator. + /// + /// Enumerator + IEnumerator IEnumerable.GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + #endregion Enumerators + + #region Public Members + /// + /// Add values to Multimap + /// + /// Key value pair + public void Add(KeyValuePair> item) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + + /// + /// Add Multimap to Multimap + /// + /// Multimap + public void Add(Multimap multimap) + { + foreach (var item in multimap) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + + /// + /// Clear Multimap + /// + public void Clear() + { + _dictionary.Clear(); + } + + /// + /// Determines whether Multimap contains the specified item. + /// + /// Key value pair + /// Method needs to be implemented + /// true if the Multimap contains the item; otherwise, false. + public bool Contains(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Copy items of the Multimap to an array, + /// starting at a particular array index. + /// + /// The array that is the destination of the items copied + /// from Multimap. The array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + /// Method needs to be implemented + public void CopyTo(KeyValuePair>[] array, int arrayIndex) + { + throw new NotImplementedException(); + } + + /// + /// Removes the specified item from the Multimap. + /// + /// Key value pair + /// true if the item is successfully removed; otherwise, false. + /// Method needs to be implemented + public bool Remove(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Gets the number of items contained in the Multimap. + /// + public int Count => _dictionary.Count; + + /// + /// Gets a value indicating whether the Multimap is read-only. + /// + public bool IsReadOnly => false; + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add the value to Multimap. + public void Add(TKey key, IList value) + { + if (value != null && value.Count > 0) + { + if (_dictionary.TryGetValue(key, out var list)) + { + foreach (var k in value) list.Add(k); + } + else + { + list = new List(value); + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + } + + /// + /// Determines whether the Multimap contains an item with the specified key. + /// + /// The key to locate in the Multimap. + /// true if the Multimap contains an item with + /// the key; otherwise, false. + public bool ContainsKey(TKey key) + { + return _dictionary.ContainsKey(key); + } + + /// + /// Removes item with the specified key from the Multimap. + /// + /// The key to locate in the Multimap. + /// true if the item is successfully removed; otherwise, false. + public bool Remove(TKey key) + { + return TryRemove(key, out var _); + } + + /// + /// Gets the value associated with the specified key. + /// + /// The key whose value to get. + /// When this method returns, the value associated with the specified key, if the + /// key is found; otherwise, the default value for the type of the value parameter. + /// This parameter is passed uninitialized. + /// true if the object that implements Multimap contains + /// an item with the specified key; otherwise, false. + public bool TryGetValue(TKey key, out IList value) + { + return _dictionary.TryGetValue(key, out value); + } + + /// + /// Gets or sets the item with the specified key. + /// + /// The key of the item to get or set. + /// The value of the specified key. + public IList this[TKey key] + { + get => _dictionary[key]; + set => _dictionary[key] = value; + } + + /// + /// Gets a System.Collections.Generic.ICollection containing the keys of the Multimap. + /// + public ICollection Keys => _dictionary.Keys; + + /// + /// Gets a System.Collections.Generic.ICollection containing the values of the Multimap. + /// + public ICollection> Values => _dictionary.Values; + + /// + /// Copy the items of the Multimap to an System.Array, + /// starting at a particular System.Array index. + /// + /// The one-dimensional System.Array that is the destination of the items copied + /// from Multimap. The System.Array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + public void CopyTo(Array array, int index) + { + ((ICollection)_dictionary).CopyTo(array, index); + } + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add value to Multimap. + public void Add(TKey key, TValue value) + { + if (value != null) + { + if (_dictionary.TryGetValue(key, out var list)) + { + list.Add(value); + } + else + { + list = new List { value }; + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add value to Multimap."); + } + } + } + + #endregion Public Members + + #region Private Members + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryRemove(TKey key, out IList value) + { + _dictionary.TryGetValue(key, out value); + return _dictionary.Remove(key); + } + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryAdd(TKey key, IList value) + { + try + { + _dictionary.Add(key, value); + } + catch (ArgumentException) + { + return false; + } + + return true; + } + #endregion Private Members + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/OpenAPIDateConverter.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/OpenAPIDateConverter.mustache new file mode 100644 index 00000000000..d7905102576 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/OpenAPIDateConverter.mustache @@ -0,0 +1,21 @@ +{{>partial_header}} +using Newtonsoft.Json.Converters; + +namespace {{packageName}}.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/README.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/README.mustache new file mode 100644 index 00000000000..b15d2a25bf1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/README.mustache @@ -0,0 +1,270 @@ +# {{packageName}} - the C# library for the {{appName}} + +{{#appDescriptionWithNewLines}} +{{{appDescriptionWithNewLines}}} +{{/appDescriptionWithNewLines}} + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: {{appVersion}} +- SDK version: {{packageVersion}} +{{^hideGenerationTimestamp}} +- Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} +- Build package: {{generatorClass}} +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + + +## Frameworks supported +{{#netStandard}} +- .NET Core >=1.0 +- .NET Framework >=4.6 +- Mono/Xamarin >=vNext +{{/netStandard}} + + +## Dependencies + +{{#useRestSharp}} +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.11.7 or later +{{/useRestSharp}} +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 12.0.3 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later +{{#useCompareNetObjects}} +- [CompareNETObjects](https://www.nuget.org/packages/CompareNETObjects) - 4.61.0 or later +{{/useCompareNetObjects}} +{{#validatable}} +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later +{{/validatable}} + +The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: +``` +{{#useRestSharp}} +Install-Package RestSharp +{{/useRestSharp}} +Install-Package Newtonsoft.Json +Install-Package JsonSubTypes +{{#validatable}} +Install-Package System.ComponentModel.Annotations +{{/validatable}} +{{#useCompareNetObjects}} +Install-Package CompareNETObjects +{{/useCompareNetObjects}} +``` +{{#useRestSharp}} + +NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742). +NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406). + +{{/useRestSharp}} + +## Installation +{{#netStandard}} +Generate the DLL using your preferred tool (e.g. `dotnet build`) +{{/netStandard}} +{{^netStandard}} +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` +{{/netStandard}} + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; +``` +{{^netStandard}} + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out {{packageName}}.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + +{{/netStandard}} + +## Usage + +To use the API client with a HTTP proxy, setup a `System.Net.WebProxy` +```csharp +Configuration c = new Configuration(); +System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/"); +webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials; +c.Proxy = webProxy; +``` +{{#useHttpClient}} + +### Connections +Each ApiClass (properly the ApiClient inside it) will create an istance of HttpClient. It will use that for the entire lifecycle and dispose it when called the Dispose method. + +To better manager the connections it's a common practice to reuse the HttpClient and HttpClientHander (see [here](https://docs.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests#issues-with-the-original-httpclient-class-available-in-net) for details). To use your own HttpClient instance just pass it to the ApiClass constructor. + +```csharp +HttpClientHandler yourHandler = new HttpClientHandler(); +HttpClient yourHttpClient = new HttpClient(yourHandler); +var api = new YourApiClass(yourHttpClient, yourHandler); +``` + +If you want to use an HttpClient and don't have access to the handler, for example in a DI context in Asp.net Core when using IHttpClientFactory. + +```csharp +HttpClient yourHttpClient = new HttpClient(); +var api = new YourApiClass(yourHttpClient); +``` +You'll loose some configuration settings, the features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. You need to either manually handle those in your setup of the HttpClient or they won't be available. + +Here an example of DI setup in a sample web project: + +```csharp +services.AddHttpClient(httpClient => + new PetApi(httpClient)); +``` + +{{/useHttpClient}} + + +## Getting Started + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public static void Main() + { +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} + Configuration config = new Configuration(); + config.BasePath = "{{{basePath}}}"; + {{#hasAuthMethods}} + {{#authMethods}} + {{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer token for authorization: {{{name}}} + config.AccessToken = "YOUR_BEARER_TOKEN"; + {{/isBasicBearer}} + {{#isApiKey}} + // Configure API key authorization: {{{name}}} + config.ApiKey.Add("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.ApiKeyPrefix.Add("{{{keyParamName}}}", "Bearer"); + {{/isApiKey}} + {{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + config.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isOAuth}} + {{/authMethods}} + + {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} + var apiInstance = new {{classname}}(config); + {{/useHttpClient}} + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (ApiException e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *{{{basePath}}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{{summary}}}{{/summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + + +## Documentation for Models + +{{#modelPackage}} +{{#models}}{{#model}} - [{{{modelPackage}}}.{{{classname}}}]({{modelDocPath}}{{{classname}}}.md) +{{/model}}{{/models}} +{{/modelPackage}} +{{^modelPackage}} +No model defined in this package +{{/modelPackage}} + + +## Documentation for Authorization + +{{^authMethods}} +All endpoints do not require authorization. +{{/authMethods}} +{{#authMethods}} +{{#last}} +Authentication schemes defined for the API: +{{/last}} +{{/authMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasicBasic}}- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}}- **Type**: Bearer Authentication +{{/isBasicBearer}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ReadOnlyDictionary.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ReadOnlyDictionary.mustache new file mode 100644 index 00000000000..1299b2436be --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/ReadOnlyDictionary.mustache @@ -0,0 +1,137 @@ +{{>partial_header}} +using System; +using System.Collections; +using System.Collections.Generic; +using System.Runtime.Serialization; + +namespace {{packageName}}.Client +{ + public class ReadOnlyDictionary : IDictionary + { + private IDictionary _dictionaryImplementation; + public IEnumerator> GetEnumerator() + { + return _dictionaryImplementation.GetEnumerator(); + } + + public ReadOnlyDictionary() + { + _dictionaryImplementation = new Dictionary(); + } + + public ReadOnlyDictionary(IDictionary dictionaryImplementation) + { + if (dictionaryImplementation == null) throw new ArgumentNullException("dictionaryImplementation"); + _dictionaryImplementation = dictionaryImplementation; + } + + IEnumerator IEnumerable.GetEnumerator() + { + return ((IEnumerable) _dictionaryImplementation).GetEnumerator(); + } + + public void Add(KeyValuePair item) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public void Clear() + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public bool Contains(KeyValuePair item) + { + return _dictionaryImplementation.Contains(item); + } + + public void CopyTo(KeyValuePair[] array, int arrayIndex) + { + _dictionaryImplementation.CopyTo(array, arrayIndex); + } + + public bool Remove(KeyValuePair item) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public int Count + { + get { return _dictionaryImplementation.Count; } + } + + public bool IsReadOnly + { + get { return true; } + } + + public void Add(T key, K value) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public bool ContainsKey(T key) + { + return _dictionaryImplementation.ContainsKey(key); + } + + public bool Remove(T key) + { + throw new ReadonlyOperationException("This instance is readonly."); + } + + public bool TryGetValue(T key, out K value) + { + return _dictionaryImplementation.TryGetValue(key, out value); + } + + public K this[T key] + { + get { return _dictionaryImplementation[key]; } + set + { + throw new ReadonlyOperationException("This instance is readonly."); + + } + } + + public ICollection Keys + { + get { return _dictionaryImplementation.Keys; } + } + + public ICollection Values + { + get { return _dictionaryImplementation.Values; } + } + } + + [Serializable] + public class ReadonlyOperationException : Exception + { + // + // For guidelines regarding the creation of new exception types, see + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpgenref/html/cpconerrorraisinghandlingguidelines.asp + // and + // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dncscol/html/csharp07192001.asp + // + + public ReadonlyOperationException() + { + } + + public ReadonlyOperationException(string message) : base(message) + { + } + + public ReadonlyOperationException(string message, Exception inner) : base(message, inner) + { + } + + protected ReadonlyOperationException( + SerializationInfo info, + StreamingContext context) : base(info, context) + { + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RequestOptions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RequestOptions.mustache new file mode 100644 index 00000000000..dc924c733c1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RequestOptions.mustache @@ -0,0 +1,66 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Dictionary FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Dictionary(); + Cookies = new List(); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RetryConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RetryConfiguration.mustache new file mode 100644 index 00000000000..29aa6092681 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/RetryConfiguration.mustache @@ -0,0 +1,39 @@ +using Polly; +{{#useRestSharp}} +using RestSharp; +{{/useRestSharp}} +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} + +namespace {{packageName}}.Client +{ + /// + /// Configuration class to set the polly retry policies to be applied to the requests. + /// + public class RetryConfiguration + { +{{#useRestSharp}} + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } +{{/useRestSharp}} +{{#useHttpClient}} + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } +{{/useHttpClient}} + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Solution.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Solution.mustache new file mode 100644 index 00000000000..112cc3dc405 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/Solution.mustache @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio {{^netStandard}}2012{{/netStandard}}{{#netStandard}}14{{/netStandard}} +VisualStudioVersion = {{^netStandard}}12.0.0.0{{/netStandard}}{{#netStandard}}14.0.25420.1{{/netStandard}} +MinimumVisualStudioVersion = {{^netStandard}}10.0.0.1{{/netStandard}}{{#netStandard}}10.0.40219.1{{/netStandard}} +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{packageName}}", "src\{{packageName}}\{{packageName}}.csproj", "{{packageGuid}}" +EndProject +{{^excludeTests}}Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "{{testPackageName}}", "src\{{testPackageName}}\{{testPackageName}}.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +{{/excludeTests}}Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {{packageGuid}}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {{packageGuid}}.Debug|Any CPU.Build.0 = Debug|Any CPU + {{packageGuid}}.Release|Any CPU.ActiveCfg = Release|Any CPU + {{packageGuid}}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/TestProject.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/TestProject.mustache new file mode 100644 index 00000000000..b1a50ae778e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/TestProject.mustache @@ -0,0 +1,36 @@ + + + + + false + Properties + {{testPackageName}} + {{testPackageName}} + {{testTargetFramework}} + false + 512 + + + + + + + + + {{packageGuid}} + {{packageName}} + + + + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/WebRequestPathBuilder.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/WebRequestPathBuilder.mustache new file mode 100644 index 00000000000..8175f0e5757 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/WebRequestPathBuilder.mustache @@ -0,0 +1,44 @@ +{{>partial_header}} +using System.Collections.Generic; + +namespace {{packageName}}.Client +{ + /// + /// A URI builder + /// + class WebRequestPathBuilder + { + private string _baseUrl; + private string _path; + private string _query = "?"; + public WebRequestPathBuilder(string baseUrl, string path) + { + _baseUrl = baseUrl; + _path = path; + } + + public void AddPathParameters(Dictionary parameters) + { + foreach (var parameter in parameters) + { + _path = _path.Replace("{" + parameter.Key + "}", parameter.Value); + } + } + + public void AddQueryParameters(Multimap parameters) + { + foreach (var parameter in parameters) + { + foreach (var value in parameter.Value) + { + _query = _query + parameter.Key + "=" + value + "&"; + } + } + } + + public string GetFullUri() + { + return _baseUrl + _path + _query.Substring(0, _query.Length - 1); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api.mustache new file mode 100644 index 00000000000..8d84eecefb4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api.mustache @@ -0,0 +1,626 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using {{packageName}}.Client; +{{#hasImport}}using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.{{apiPackage}} +{ + {{#operations}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Sync : IApiAccessor + { + #region Synchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + {{#notes}} + /// + /// {{notes}} + /// + {{/notes}} + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} + ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + {{/operation}} + #endregion Synchronous Operations + } + + {{#supportsAsync}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Async : IApiAccessor + { + #region Asynchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} + System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + {{/operation}} + #endregion Asynchronous Operations + } + {{/supportsAsync}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}} : {{interfacePrefix}}{{classname}}Sync{{#supportsAsync}}, {{interfacePrefix}}{{classname}}Async{{/supportsAsync}} + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} partial class {{classname}} : {{interfacePrefix}}{{classname}} + { + private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public {{classname}}() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public {{classname}}(string basePath) + { + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.Client = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{#supportsAsync}} + this.AsynchronousClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public {{classname}}({{packageName}}.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{#supportsAsync}} + this.AsynchronousClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access.{{#supportsAsync}} + /// The client interface for asynchronous API access.{{/supportsAsync}} + /// The configuration object. + public {{classname}}({{packageName}}.Client.ISynchronousClient client, {{#supportsAsync}}{{packageName}}.Client.IAsynchronousClient asyncClient, {{/supportsAsync}}{{packageName}}.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + {{#supportsAsync}} + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + {{/supportsAsync}} + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + {{#supportsAsync}} + this.AsynchronousClient = asyncClient; + {{/supportsAsync}} + this.Configuration = configuration; + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + {{#supportsAsync}} + /// + /// The client for accessing this underlying API asynchronously. + /// + public {{packageName}}.Client.IAsynchronousClient AsynchronousClient { get; set; } + {{/supportsAsync}} + + /// + /// The client for accessing this underlying API synchronously. + /// + public {{packageName}}.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public {{packageName}}.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public {{packageName}}.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + return localVarResponse.Data;{{/returnType}}{{^returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} + public {{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + {{#isDeepObject}} + {{#items.vars}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isDeepObject}} + {{#items.vars}} + if ({{paramName}}.{{name}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + } + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + var localVarResponse = this.Client.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{#supportsAsync}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); + return localVarResponse.Data;{{/returnType}}{{^returnType}}await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false);{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} + public async System.Threading.Tasks.Task<{{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}}, {{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}Async<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{/supportsAsync}} + {{/operation}} + } + {{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_doc.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_doc.mustache new file mode 100644 index 00000000000..d12ee22ea38 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_doc.mustache @@ -0,0 +1,134 @@ +# {{packageName}}.{{apiPackage}}.{{classname}}{{#description}} +{{description}}{{/description}} + +All URIs are relative to *{{{basePath}}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationIdLowerCase}}) | **{{httpMethod}}** {{path}} | {{#summary}}{{summary}}{{/summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +# **{{{operationId}}}** +> {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}} ({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = null{{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + +{{{summary}}}{{#notes}} + +{{{notes}}}{{/notes}} + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +{{#useHttpClient}} +using System.Net.Http; +{{/useHttpClient}} +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.Client; +using {{packageName}}.{{modelPackage}}; + +namespace Example +{ + public class {{operationId}}Example + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "{{{basePath}}}"; + {{#hasAuthMethods}} + {{#authMethods}} + {{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + config.Username = "YOUR_USERNAME"; + config.Password = "YOUR_PASSWORD"; + {{/isBasicBasic}} + {{#isBasicBearer}} + // Configure Bearer token for authorization: {{{name}}} + config.AccessToken = "YOUR_BEARER_TOKEN"; + {{/isBasicBearer}} + {{#isApiKey}} + // Configure API key authorization: {{{name}}} + config.AddApiKey("{{{keyParamName}}}", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("{{{keyParamName}}}", "Bearer"); + {{/isApiKey}} + {{#isOAuth}} + // Configure OAuth2 access token for authorization: {{{name}}} + config.AccessToken = "YOUR_ACCESS_TOKEN"; + {{/isOAuth}} + {{/authMethods}} + + {{/hasAuthMethods}} + {{#useHttpClient}} + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new {{classname}}(httpClient, config, httpClientHandler); + {{/useHttpClient}} + {{^useHttpClient}} + var apiInstance = new {{classname}}(config); + {{/useHttpClient}} + {{#allParams}} + {{#isPrimitiveType}} + var {{paramName}} = {{{example}}}; // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{^isPrimitiveType}} + var {{paramName}} = new {{{dataType}}}(); // {{{dataType}}} | {{{description}}}{{^required}} (optional) {{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/isPrimitiveType}} + {{/allParams}} + + try + { + {{#summary}} + // {{{.}}} + {{/summary}} + {{#returnType}}{{{returnType}}} result = {{/returnType}}apiInstance.{{{operationId}}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{#returnType}} + Debug.WriteLine(result);{{/returnType}} + } + catch (ApiException e) + { + Debug.Print("Exception when calling {{classname}}.{{operationId}}: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isFile}}**{{dataType}}**{{/isFile}}{{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{^isFile}}[**{{dataType}}**]({{#isContainer}}{{baseType}}{{/isContainer}}{{^isContainer}}{{dataType}}{{/isContainer}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{defaultValue}}]{{/defaultValue}} +{{/allParams}} + +### Return type + +{{#returnType}}{{#returnTypeIsPrimitive}}**{{{returnType}}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{{name}}}](../README.md#{{{name}}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + + - **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} + - **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
    {{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +[[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) + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_test.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_test.mustache new file mode 100644 index 00000000000..02ca26b5f16 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/api_test.mustache @@ -0,0 +1,73 @@ +{{>partial_header}} +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +{{#useRestSharp}} +using RestSharp; +{{/useRestSharp}} +using Xunit; + +using {{packageName}}.Client; +using {{packageName}}.{{apiPackage}}; +{{#hasImport}} +// uncomment below to import models +//using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.Test.Api +{ + /// + /// Class for testing {{classname}} + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class {{classname}}Tests : IDisposable + { + private {{classname}} instance; + + public {{classname}}Tests() + { + instance = new {{classname}}(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of {{classname}} + /// + [Fact] + public void {{operationId}}InstanceTest() + { + // TODO uncomment below to test 'IsType' {{classname}} + //Assert.IsType<{{classname}}>(instance); + } + {{#operations}} + {{#operation}} + + /// + /// Test {{operationId}} + /// + [Fact] + public void {{operationId}}Test() + { + // TODO uncomment below to test the method and replace null with proper value + {{#allParams}} + //{{{dataType}}} {{paramName}} = null; + {{/allParams}} + //{{#returnType}}var response = {{/returnType}}instance.{{operationId}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + {{#returnType}} + //Assert.IsType<{{{returnType}}}>(response); + {{/returnType}} + } + {{/operation}} + {{/operations}} + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/appveyor.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/appveyor.mustache new file mode 100644 index 00000000000..eb85fc2a85b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/appveyor.mustache @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\{{{packageName}}}\{{{packageName}}}.csproj -o ../../output -c Release --no-build diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/functions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/functions.mustache new file mode 100644 index 00000000000..4709282dead --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/functions.mustache @@ -0,0 +1,28 @@ +{{>partial_header}} + +using System; +using System.Net; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Extensions.Http; + +namespace {{packageName}}.{{apiPackage}} +{ {{#operations}} + public partial {{#classModifier}}{{classModifier}} {{/classModifier}}class {{classname}} + { {{#operation}} + [FunctionName("{{classname}}_{{operationId}}")] + public async Task _{{operationId}}([HttpTrigger(AuthorizationLevel.Anonymous, "{{httpMethod}}", Route = "{{{apiBasePath}}}{{{path}}}")]HttpRequest req, ExecutionContext context{{#allParams}}{{#isPathParam}}, {{>pathParam}}{{/isPathParam}}{{/allParams}}) + { + var method = this.GetType().GetMethod("{{operationId}}"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context{{#allParams}}{{#isPathParam}}, {{/isPathParam}}{{/allParams}} })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + {{/operation}} + } +} + {{/operations}} + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/git_push.sh.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/git_push.sh.mustache new file mode 100644 index 00000000000..8b3f689c912 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/git_push.sh.mustache @@ -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="{{{gitHost}}}" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="{{{gitUserId}}}" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="{{{gitRepoId}}}" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="{{{releaseNote}}}" + 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/modules/openapi-generator/src/main/resources/csharp-netcore-functions/gitignore.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/gitignore.mustache new file mode 100644 index 00000000000..1ee53850b84 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/gitignore.mustache @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache new file mode 100644 index 00000000000..e9c39ea9f6d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/ApiClient.mustache @@ -0,0 +1,739 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +{{^netStandard}} +using System.Web; +{{/netStandard}} +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +{{#useWebRequest}} +using System.Net.Http; +{{/useWebRequest}} +using System.Net.Http; +using System.Net.Http.Headers; +{{#supportsRetry}} +using Polly; +{{/supportsRetry}} + +namespace {{packageName}}.Client +{ + /// + /// To Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is {{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return (({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public async Task Deserialize(HttpResponseMessage response) + { + var result = (T) await Deserialize(response, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal async Task Deserialize(HttpResponseMessage response, Type type) + { + IList headers = response.Headers.Select(x => x.Key + "=" + x.Value).ToList(); + + if (type == typeof(byte[])) // return byte array + { + return await response.Content.ReadAsByteArrayAsync(); + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = await response.Content.ReadAsByteArrayAsync(); + if (headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(await response.Content.ReadAsStringAsync(), null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(await response.Content.ReadAsStringAsync(), type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync(), type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), + /// encapsulating general REST accessor use cases. + /// + /// + /// The Dispose method will manage the HttpClient lifecycle when not passed by constructor. + /// + {{>visibility}} partial class ApiClient : IDisposable, ISynchronousClient{{#supportsAsync}}, IAsynchronousClient{{/supportsAsync}} + { + private readonly string _baseUrl; + + private readonly HttpClientHandler _httpClientHandler; + private readonly HttpClient _httpClient; + private readonly bool _disposeClient; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accomodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + public ApiClient() : + this({{packageName}}.Client.GlobalConfiguration.Instance.BasePath) + { + } + + /// + /// Initializes a new instance of the . + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = new HttpClientHandler(); + _httpClient = new HttpClient(_httpClientHandler, true); + _disposeClient = true; + _baseUrl = basePath; + } + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, HttpClientHandler handler = null) : + this(client, {{packageName}}.Client.GlobalConfiguration.Instance.BasePath, handler) + { + } + + /// + /// Initializes a new instance of the . + /// + /// An instance of HttpClient. + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public ApiClient(HttpClient client, string basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client cannot be null"); + if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); + + _httpClientHandler = handler; + _httpClient = client; + _baseUrl = basePath; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + if(_disposeClient) { + _httpClient.Dispose(); + } + } + + /// Prepares multipart/form-data content + {{! TODO: Add handling of improper usage }} + HttpContent PrepareMultipartFormDataContent(RequestOptions options) + { + string boundary = "---------" + Guid.NewGuid().ToString().ToUpperInvariant(); + var multipartContent = new MultipartFormDataContent(boundary); + foreach (var formParameter in options.FormParameters) + { + multipartContent.Add(new StringContent(formParameter.Value), formParameter.Key); + } + + if (options.FileParameters != null && options.FileParameters.Count > 0) + { + foreach (var fileParam in options.FileParameters) + { + var content = new StreamContent(fileParam.Value.Content); + content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); + multipartContent.Add(content, fileParam.Key, + fileParam.Value.Name); + } + } + return multipartContent; + } + + /// + /// Provides all logic for constructing a new HttpRequestMessage. + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the a HttpRequestMessage. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new HttpRequestMessage instance. + /// + private HttpRequestMessage NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + WebRequestPathBuilder builder = new WebRequestPathBuilder(_baseUrl, path); + + builder.AddPathParameters(options.PathParameters); + + builder.AddQueryParameters(options.QueryParameters); + + HttpRequestMessage request = new HttpRequestMessage(method, builder.GetFullUri()); + + if (configuration.UserAgent != null) + { + request.Headers.TryAddWithoutValidation("User-Agent", configuration.UserAgent); + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.Headers.Add(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + // Todo make content headers actually content headers + request.Headers.TryAddWithoutValidation(headerParam.Key, value); + } + } + } + + List> contentList = new List>(); + + string contentType = null; + if (options.HeaderParameters != null && options.HeaderParameters.ContainsKey("Content-Type")) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes.FirstOrDefault(); + } + + {{!// TODO Add error handling in case of improper usage}} + if (contentType == "multipart/form-data") + { + request.Content = PrepareMultipartFormDataContent(options); + } + else if (contentType == "application/x-www-form-urlencoded") + { + request.Content = new FormUrlEncodedContent(options.FormParameters); + } + else + { + if (options.Data != null) + { + if (options.Data is FileParameter fp) + { + contentType = contentType ?? "application/octet-stream"; + + var streamContent = new StreamContent(fp.Content); + streamContent.Headers.ContentType = new MediaTypeHeaderValue(contentType); + request.Content = streamContent; + } + else + { + var serializer = new CustomJsonCodec(SerializerSettings, configuration); + request.Content = new StringContent(serializer.Serialize(options.Data), new UTF8Encoding(), + "application/json"); + } + } + } + + + + // TODO provide an alternative that allows cookies per request instead of per API client + if (options.Cookies != null && options.Cookies.Count > 0) + { + request.Properties["CookieContainer"] = options.Cookies; + } + + return request; + } + + partial void InterceptRequest(HttpRequestMessage req); + partial void InterceptResponse(HttpRequestMessage req, HttpResponseMessage response); + + private async Task> ToApiResponse(HttpResponseMessage response, object responseData, Uri uri) + { + T result = (T) responseData; + string rawContent = await response.Content.ReadAsStringAsync(); + + var transformed = new ApiResponse(response.StatusCode, new Multimap({{#caseInsensitiveResponseHeaders}}StringComparer.OrdinalIgnoreCase{{/caseInsensitiveResponseHeaders}}), result, rawContent) + { + ErrorText = response.ReasonPhrase, + Cookies = new List() + }; + + // process response headers, e.g. Access-Control-Allow-Methods + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + // process response content headers, e.g. Content-Type + if (response.Content.Headers != null) + { + foreach (var responseHeader in response.Content.Headers) + { + transformed.Headers.Add(responseHeader.Key, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (_httpClientHandler != null && response != null) + { + try { + foreach (Cookie cookie in _httpClientHandler.CookieContainer.GetCookies(uri)) + { + transformed.Cookies.Add(cookie); + } + } + catch (PlatformNotSupportedException) {} + } + + return transformed; + } + + private ApiResponse Exec(HttpRequestMessage req, IReadableConfiguration configuration) + { + return ExecAsync(req, configuration).GetAwaiter().GetResult(); + } + + private async Task> ExecAsync(HttpRequestMessage req, + IReadableConfiguration configuration, + System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var deserializer = new CustomJsonCodec(SerializerSettings, configuration); + + var finalToken = cancellationToken; + + if (configuration.Timeout > 0) + { + var tokenSource = new CancellationTokenSource(configuration.Timeout); + finalToken = CancellationTokenSource.CreateLinkedTokenSource(finalToken, tokenSource.Token).Token; + } + + if (configuration.Proxy != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `Proxy` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.Proxy = configuration.Proxy; + } + + if (configuration.ClientCertificates != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Configuration `ClientCertificates` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + _httpClientHandler.ClientCertificates.AddRange(configuration.ClientCertificates); + } + + var cookieContainer = req.Properties.ContainsKey("CookieContainer") ? req.Properties["CookieContainer"] as List : null; + + if (cookieContainer != null) + { + if(_httpClientHandler == null) throw new InvalidOperationException("Request property `CookieContainer` not supported when the client is explicitly created without an HttpClientHandler, use the proper constructor."); + foreach (var cookie in cookieContainer) + { + _httpClientHandler.CookieContainer.Add(cookie); + } + } + + InterceptRequest(req); + + HttpResponseMessage response; +{{#supportsRetry}} + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy + .ExecuteAndCaptureAsync(() => _httpClient.SendAsync(req, cancellationToken)) + .ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? + policyResult.Result : new HttpResponseMessage() + { + ReasonPhrase = policyResult.FinalException.ToString(), + RequestMessage = req + }; + } + else + { +{{/supportsRetry}} + response = await _httpClient.SendAsync(req, cancellationToken).ConfigureAwait(false); +{{#supportsRetry}} + } +{{/supportsRetry}} + + if (!response.IsSuccessStatusCode) + { + return await ToApiResponse(response, default(T), req.RequestUri); + } + + object responseData = await deserializer.Deserialize(response); + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof({{{packageName}}}.{{modelPackage}}.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + responseData = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + responseData = (T) (object) await response.Content.ReadAsStreamAsync(); + } + + InterceptResponse(req, response); + + return await ToApiResponse(response, responseData, req.RequestUri); + } + + {{#supportsAsync}} + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(new HttpMethod("PATCH"), path, options, config), config, cancellationToken); + } + #endregion IAsynchronousClient + {{/supportsAsync}} + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(new HttpMethod("PATCH"), path, options, config), config); + } + #endregion ISynchronousClient + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/FileParameter.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/FileParameter.mustache new file mode 100644 index 00000000000..3fa243ed54f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/FileParameter.mustache @@ -0,0 +1,54 @@ +{{>partial_header}} + +using System.IO; + +namespace {{packageName}}.Client +{ + + /// + /// Represents a File passed to the API as a Parameter, allows using different backends for files + /// + public class FileParameter + { + /// + /// The filename + /// + public string Name { get; set; } = "no_name_provided"; + + /// + /// The content of the file + /// + public Stream Content { get; set; } + + /// + /// Construct a FileParameter just from the contents, will extract the filename from a filestream + /// + /// The file content + public FileParameter(Stream content) + { + if (content is FileStream fs) + { + Name = fs.Name; + } + Content = content; + } + + /// + /// Construct a FileParameter from name and content + /// + /// The filename + /// The file content + public FileParameter(string filename, Stream content) + { + Name = filename; + Content = content; + } + + /// + /// Implicit conversion of stream to file parameter. Useful for backwards compatibility. + /// + /// Stream to convert + /// FileParameter + public static implicit operator FileParameter(Stream s) => new FileParameter(s); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/RequestOptions.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/RequestOptions.mustache new file mode 100644 index 00000000000..bc5a8e348b8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/RequestOptions.mustache @@ -0,0 +1,66 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace {{packageName}}.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Dictionary FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Dictionary(); + Cookies = new List(); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/api.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/api.mustache new file mode 100644 index 00000000000..20ddfe96b98 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/api.mustache @@ -0,0 +1,724 @@ +{{>partial_header}} + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Net.Mime; +using {{packageName}}.Client; +{{#hasImport}}using {{packageName}}.{{modelPackage}}; +{{/hasImport}} + +namespace {{packageName}}.{{apiPackage}} +{ + {{#operations}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Sync : IApiAccessor + { + #region Synchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + {{#notes}} + /// + /// {{notes}} + /// + {{/notes}} + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} + ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}); + {{/operation}} + #endregion Synchronous Operations + } + + {{#supportsAsync}} + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}}Async : IApiAccessor + { + #region Asynchronous Operations + {{#operation}} + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{#returnType}}System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// {{summary}} + /// + /// + /// {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} + System.Threading.Tasks.Task> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + {{/operation}} + #endregion Asynchronous Operations + } + {{/supportsAsync}} + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} interface {{interfacePrefix}}{{classname}} : {{interfacePrefix}}{{classname}}Sync{{#supportsAsync}}, {{interfacePrefix}}{{classname}}Async{{/supportsAsync}} + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + {{>visibility}} partial class {{classname}} : IDisposable, {{interfacePrefix}}{{classname}} + { + private {{packageName}}.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + /// + public {{classname}}() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + /// The target service's base path in URL format. + /// + /// + public {{classname}}(string basePath) + { + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class using Configuration object. + /// **IMPORTANT** This will also create an istance of HttpClient, which is less than ideal. + /// It's better to reuse the HttpClient and HttpClientHander. + /// + /// An instance of Configuration. + /// + /// + public {{classname}}({{packageName}}.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(this.Configuration.BasePath); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class. + /// + /// An instance of HttpClient. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public {{classname}}(HttpClient client, HttpClientHandler handler = null) : this(client, (string)null, handler) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// An instance of HttpClient. + /// The target service's base path in URL format. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public {{classname}}(HttpClient client, string basePath, HttpClientHandler handler = null) + { + if (client == null) throw new ArgumentNullException("client"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + new {{packageName}}.Client.Configuration { BasePath = basePath } + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath, handler); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class using Configuration object. + /// + /// An instance of HttpClient. + /// An instance of Configuration. + /// An optional instance of HttpClientHandler that is used by HttpClient. + /// + /// + /// + /// Some configuration settings will not be applied without passing an HttpClientHandler. + /// The features affected are: Setting and Retrieving Cookies, Client Certificates, Proxy settings. + /// + public {{classname}}(HttpClient client, {{packageName}}.Client.Configuration configuration, HttpClientHandler handler = null) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + if (client == null) throw new ArgumentNullException("client"); + + this.Configuration = {{packageName}}.Client.Configuration.MergeConfigurations( + {{packageName}}.Client.GlobalConfiguration.Instance, + configuration + ); + this.ApiClient = new {{packageName}}.Client.ApiClient(client, this.Configuration.BasePath, handler); + this.Client = this.ApiClient; + {{#supportsAsync}} + this.AsynchronousClient = this.ApiClient; + {{/supportsAsync}} + ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access.{{#supportsAsync}} + /// The client interface for asynchronous API access.{{/supportsAsync}} + /// The configuration object. + /// + public {{classname}}({{packageName}}.Client.ISynchronousClient client, {{#supportsAsync}}{{packageName}}.Client.IAsynchronousClient asyncClient, {{/supportsAsync}}{{packageName}}.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + {{#supportsAsync}} + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + {{/supportsAsync}} + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + {{#supportsAsync}} + this.AsynchronousClient = asyncClient; + {{/supportsAsync}} + this.Configuration = configuration; + this.ExceptionFactory = {{packageName}}.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Disposes resources if they were created by us + /// + public void Dispose() + { + this.ApiClient?.Dispose(); + } + + /// + /// Holds the ApiClient if created + /// + public {{packageName}}.Client.ApiClient ApiClient { get; set; } = null; + + {{#supportsAsync}} + /// + /// The client for accessing this underlying API asynchronously. + /// + public {{packageName}}.Client.IAsynchronousClient AsynchronousClient { get; set; } + {{/supportsAsync}} + + /// + /// The client for accessing this underlying API synchronously. + /// + public {{packageName}}.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public {{packageName}}.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public {{packageName}}.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + {{#operation}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// {{#returnType}}{{returnType}}{{/returnType}} + public {{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}void{{/returnType}} {{operationId}}({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = {{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + return localVarResponse.Data;{{/returnType}}{{^returnType}}{{operationId}}WithHttpInfo({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}});{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}}/// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}}/// ApiResponse of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}Object(void){{/returnType}} + public {{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}> {{operationId}}WithHttpInfo({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + {{#isDeepObject}} + {{#items.vars}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isDeepObject}} + {{#items.vars}} + if ({{paramName}}.{{name}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}}.{{name}})); + } + {{/items.vars}} + {{^items}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("deepObject", "{{baseName}}", {{paramName}})); + {{/items}} + {{/isDeepObject}} + {{^isDeepObject}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/isDeepObject}} + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + var localVarResponse = this.Client.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{#supportsAsync}} + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of {{#returnType}}{{returnType}}{{/returnType}}{{^returnType}}void{{/returnType}} + {{#returnType}}public async System.Threading.Tasks.Task<{{{returnType}}}>{{/returnType}}{{^returnType}}public async System.Threading.Tasks.Task{{/returnType}} {{operationId}}Async({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#returnType}}{{packageName}}.Client.ApiResponse<{{{returnType}}}> localVarResponse = await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false); + return localVarResponse.Data;{{/returnType}}{{^returnType}}await {{operationId}}WithHttpInfoAsync({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}cancellationToken).ConfigureAwait(false);{{/returnType}} + } + + /// + /// {{summary}} {{notes}} + /// + /// Thrown when fails to make API call + {{#allParams}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + {{/allParams}} + /// Cancellation Token to cancel the request. + /// Task of ApiResponse{{#returnType}} ({{returnType}}){{/returnType}} + public async System.Threading.Tasks.Task<{{packageName}}.Client.ApiResponse<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>> {{operationId}}WithHttpInfoAsync({{#allParams}}{{{dataType}}} {{paramName}}{{^required}}{{#optionalMethodArgument}} = default({{{dataType}}}){{/optionalMethodArgument}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}{{#allParams.0}}, {{/allParams.0}}System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + {{#allParams}} + {{#required}} + {{^vendorExtensions.x-csharp-value-type}} + // verify the required parameter '{{paramName}}' is set + if ({{paramName}} == null) + throw new {{packageName}}.Client.ApiException(400, "Missing required parameter '{{paramName}}' when calling {{classname}}->{{operationId}}"); + + {{/vendorExtensions.x-csharp-value-type}} + {{/required}} + {{/allParams}} + + {{packageName}}.Client.RequestOptions localVarRequestOptions = new {{packageName}}.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + {{#consumes}} + "{{{mediaType}}}"{{^-last}}, {{/-last}} + {{/consumes}} + }; + + // to determine the Accept header + string[] _accepts = new string[] { + {{#produces}} + "{{{mediaType}}}"{{^-last}},{{/-last}} + {{/produces}} + }; + + + var localVarContentType = {{packageName}}.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = {{packageName}}.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + {{#pathParams}} + {{#required}} + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.PathParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // path parameter + } + {{/required}} + {{/pathParams}} + {{#queryParams}} + {{#required}} + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("{{#collectionFormat}}{{collectionFormat}}{{/collectionFormat}}", "{{baseName}}", {{paramName}})); + } + {{/required}} + {{/queryParams}} + {{#headerParams}} + {{#required}} + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + localVarRequestOptions.HeaderParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // header parameter + } + {{/required}} + {{/headerParams}} + {{#formParams}} + {{#required}} + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + {{/required}} + {{^required}} + if ({{paramName}} != null) + { + {{#isFile}} + localVarRequestOptions.FileParameters.Add("{{baseName}}", {{paramName}}); + {{/isFile}} + {{^isFile}} + localVarRequestOptions.FormParameters.Add("{{baseName}}", {{packageName}}.Client.ClientUtils.ParameterToString({{paramName}})); // form parameter + {{/isFile}} + } + {{/required}} + {{/formParams}} + {{#bodyParam}} + localVarRequestOptions.Data = {{paramName}}; + {{/bodyParam}} + + {{#authMethods}} + // authentication ({{name}}) required + {{#isApiKey}} + {{#isKeyInCookie}} + // cookie parameter support + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.Cookies.Add(new Cookie("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInCookie}} + {{#isKeyInHeader}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.HeaderParameters.Add("{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}")); + } + {{/isKeyInHeader}} + {{#isKeyInQuery}} + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))) + { + localVarRequestOptions.QueryParameters.Add({{packageName}}.Client.ClientUtils.ParameterToMultiMap("", "{{keyParamName}}", this.Configuration.GetApiKeyWithPrefix("{{keyParamName}}"))); + } + {{/isKeyInQuery}} + {{/isApiKey}} + {{#isBasic}} + {{#isBasicBasic}} + // http basic authentication required + if (!string.IsNullOrEmpty(this.Configuration.Username) || !string.IsNullOrEmpty(this.Configuration.Password)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Basic " + {{packageName}}.Client.ClientUtils.Base64Encode(this.Configuration.Username + ":" + this.Configuration.Password)); + } + {{/isBasicBasic}} + {{#isBasicBearer}} + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isBasicBearer}} + {{/isBasic}} + {{#isOAuth}} + // oauth required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken)) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + {{/isOAuth}} + {{#isHttpSignature}} + if (this.Configuration.HttpSigningConfiguration != null) + { + var HttpSigningHeaders = this.Configuration.HttpSigningConfiguration.GetHttpSignedHeader(this.Configuration.BasePath, "{{{httpMethod}}}", "{{{path}}}", localVarRequestOptions); + foreach (var headerItem in HttpSigningHeaders) + { + if (localVarRequestOptions.HeaderParameters.ContainsKey(headerItem.Key)) + { + localVarRequestOptions.HeaderParameters[headerItem.Key] = new List() { headerItem.Value }; + } + else + { + localVarRequestOptions.HeaderParameters.Add(headerItem.Key, headerItem.Value); + } + } + } + {{/isHttpSignature}} + {{/authMethods}} + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.{{#lambda.titlecase}}{{#lambda.lowercase}}{{httpMethod}}{{/lambda.lowercase}}{{/lambda.titlecase}}Async<{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Object{{/returnType}}>("{{{path}}}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("{{operationId}}", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + {{/supportsAsync}} + {{/operation}} + } + {{/operations}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/model.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/model.mustache new file mode 100644 index 00000000000..0de1e05e514 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/libraries/httpclient/model.mustache @@ -0,0 +1,48 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +{{#models}} +{{#model}} +{{#discriminator}} +using JsonSubTypes; +{{/discriminator}} +{{/model}} +{{/models}} +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +using FileParameter = {{packageName}}.Client.FileParameter; +using OpenAPIDateConverter = {{packageName}}.Client.OpenAPIDateConverter; +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/oneOf}} +{{#aneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/aneOf}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model.mustache new file mode 100644 index 00000000000..339a6d2f76b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model.mustache @@ -0,0 +1,47 @@ +{{>partial_header}} + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +{{#models}} +{{#model}} +{{#discriminator}} +using JsonSubTypes; +{{/discriminator}} +{{/model}} +{{/models}} +{{#validatable}} +using System.ComponentModel.DataAnnotations; +{{/validatable}} +using OpenAPIDateConverter = {{packageName}}.Client.OpenAPIDateConverter; +{{#useCompareNetObjects}} +using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; +{{/useCompareNetObjects}} +{{#models}} +{{#model}} +{{#oneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/oneOf}} +{{#aneOf}} +{{#-first}} +using System.Reflection; +{{/-first}} +{{/aneOf}} + +namespace {{packageName}}.{{modelPackage}} +{ +{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{^isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{#anyOf}}{{#-first}}{{>modelAnyOf}}{{/-first}}{{/anyOf}}{{^oneOf}}{{^anyOf}}{{>modelGeneric}}{{/anyOf}}{{/oneOf}}{{/isEnum}} +{{/model}} +{{/models}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelAnyOf.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelAnyOf.mustache new file mode 100644 index 00000000000..931f7646da8 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelAnyOf.mustache @@ -0,0 +1,227 @@ + /// + /// {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} + /// + [JsonConverter(typeof({{classname}}JsonConverter))] + [DataContract(Name = "{{{name}}}")] + {{>visibility}} partial class {{classname}} : AbstractOpenAPISchema, {{#parent}}{{{parent}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}, IValidatableObject{{/validatable}} + { + {{#isNullable}} + /// + /// Initializes a new instance of the class. + /// + public {{classname}}() + { + this.IsNullable = true; + this.SchemaType= "anyOf"; + } + + {{/isNullable}} + {{#anyOf}} + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of {{{.}}}. + public {{classname}}({{{.}}} actualInstance) + { + this.IsNullable = {{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}; + this.SchemaType= "anyOf"; + this.ActualInstance = actualInstance{{^isNullable}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isNullable}}; + } + + {{/anyOf}} + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + {{#anyOf}} + {{^-first}}else {{/-first}}if (value.GetType() == typeof({{{.}}})) + { + this._actualInstance = value; + } + {{/anyOf}} + else + { + throw new ArgumentException("Invalid instance found. Must be the following types:{{#anyOf}} {{{.}}}{{^-last}},{{/-last}}{{/anyOf}}"); + } + } + } + {{#anyOf}} + + /// + /// Get the actual instance of `{{{.}}}`. If the actual instanct is not `{{{.}}}`, + /// the InvalidClassException will be thrown + /// + /// An instance of {{{.}}} + public {{{.}}} Get{{{.}}}() + { + return ({{{.}}})this.ActualInstance; + } + {{/anyOf}} + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, {{classname}}.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of {{classname}} + /// + /// JSON string + /// An instance of {{classname}} + public static {{classname}} FromJson(string jsonString) + { + {{classname}} new{{classname}} = null; + + if (jsonString == null) + { + return new{{classname}}; + } + {{#anyOf}} + + try + { + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.SerializerSettings)); + // deserialization is considered successful at this point if no exception has been thrown. + return new{{classname}}; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); + } + {{/anyOf}} + + // no match found, throw an exception + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return this.ActualInstance.Equals(input.ActualInstance); + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for {{classname}} + /// + public class {{classname}}JsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return {{classname}}.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelEnum.mustache new file mode 100644 index 00000000000..39bcd2eddc1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelEnum.mustache @@ -0,0 +1,30 @@ + /// + /// {{^description}}Defines {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// + {{#description}} + /// {{description}} + {{/description}} + {{#allowableValues}} + {{#enumVars}} + {{#-first}} + {{#isString}} + [JsonConverter(typeof(StringEnumConverter))] + {{/isString}} + {{/-first}} + {{/enumVars}} + {{/allowableValues}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}} + { + {{#allowableValues}} + {{#enumVars}} + /// + /// Enum {{name}} for value: {{{value}}} + /// + {{#isString}} + [EnumMember(Value = "{{{value}}}")] + {{/isString}} + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},{{/-last}} + + {{/enumVars}} + {{/allowableValues}} + }{{! NOTE: This model's enumVars is modified to look like CodegenProperty}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache new file mode 100644 index 00000000000..6eb1a2359d0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelGeneric.mustache @@ -0,0 +1,456 @@ + /// + /// {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} + /// + [DataContract(Name = "{{{name}}}")] + {{#discriminator}} + [JsonConverter(typeof(JsonSubtypes), "{{{discriminatorName}}}")] + {{#mappedModels}} + [JsonSubtypes.KnownSubType(typeof({{{modelName}}}), "{{^vendorExtensions.x-discriminator-value}}{{{mappingName}}}{{/vendorExtensions.x-discriminator-value}}{{#vendorExtensions.x-discriminator-value}}{{{.}}}{{/vendorExtensions.x-discriminator-value}}")] + {{/mappedModels}} + {{/discriminator}} + {{>visibility}} partial class {{classname}} : {{#parent}}{{{parent}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}, IValidatableObject{{/validatable}} + { + {{#vars}} + {{#items.isEnum}} + {{#items}} + {{^complexType}} +{{>modelInnerEnum}} + {{/complexType}} + {{/items}} + {{/items.isEnum}} + {{#isEnum}} + {{^complexType}} +{{>modelInnerEnum}} + {{/complexType}} + {{/isEnum}} + {{#isEnum}} + + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// + {{#description}} + /// {{description}} + {{/description}} + {{^conditionalSerialization}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } + {{#isReadOnly}} + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{#isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} { get; set; } + + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + + {{^isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} {{name}} + { + get{ return _{{name}};} + set + { + _{{name}} = value; + _flag{{name}} = true; + } + } + private {{#complexType}}{{{complexType}}}{{/complexType}}{{^complexType}}{{{datatypeWithEnum}}}{{/complexType}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}} _{{name}}; + private bool _flag{{name}}; + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return _flag{{name}}; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{/isEnum}} + {{/vars}} + {{#hasRequired}} + {{^hasOnlyReadOnly}} + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + {{^isAdditionalPropertiesTrue}} + protected {{classname}}() { } + {{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + protected {{classname}}() + { + this.AdditionalProperties = new Dictionary(); + } + {{/isAdditionalPropertiesTrue}} + {{/hasOnlyReadOnly}} + {{/hasRequired}} + /// + /// Initializes a new instance of the class. + /// + {{#readWriteVars}} + /// {{#description}}{{description}}{{/description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#required}} (required){{/required}}{{#defaultValue}} (default to {{defaultValue}}){{/defaultValue}}. + {{/readWriteVars}} + {{#hasOnlyReadOnly}} + [JsonConstructorAttribute] + {{/hasOnlyReadOnly}} + public {{classname}}({{#readWriteVars}}{{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{#defaultValue}}{{^isDateTime}}{{{defaultValue}}}{{/isDateTime}}{{#isDateTime}}default({{{datatypeWithEnum}}}){{/isDateTime}}{{/defaultValue}}{{^defaultValue}}default({{{datatypeWithEnum}}}{{#isEnum}}{{^isContainer}}{{^required}}?{{/required}}{{/isContainer}}{{/isEnum}}){{/defaultValue}}{{^-last}}, {{/-last}}{{/readWriteVars}}){{#parent}} : base({{#parentVars}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{^-last}}, {{/-last}}{{/parentVars}}){{/parent}} + { + {{#vars}} + {{^isInherited}} + {{^isReadOnly}} + {{#required}} + {{^conditionalSerialization}} + {{^vendorExtensions.x-csharp-value-type}} + // to ensure "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" is required (not null) + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null"); + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{^vendorExtensions.x-csharp-value-type}} + // to ensure "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" is required (not null) + this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? throw new ArgumentNullException("{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} is a required property for {{classname}} and cannot be null"); + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/conditionalSerialization}} + {{/required}} + {{/isReadOnly}} + {{/isInherited}} + {{/vars}} + {{#vars}} + {{^isInherited}} + {{^isReadOnly}} + {{^required}} + {{#defaultValue}} + {{^vendorExtensions.x-csharp-value-type}} + // use default value if no "{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}" provided + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} ?? {{{defaultValue}}}; + {{/vendorExtensions.x-csharp-value-type}} + {{#vendorExtensions.x-csharp-value-type}} + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/vendorExtensions.x-csharp-value-type}} + {{/defaultValue}} + {{^defaultValue}} + {{^conditionalSerialization}} + this.{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/conditionalSerialization}} + {{#conditionalSerialization}} + this._{{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{/conditionalSerialization}} + {{/defaultValue}} + {{/required}} + {{/isReadOnly}} + {{/isInherited}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + this.AdditionalProperties = new Dictionary(); + {{/isAdditionalPropertiesTrue}} + } + + {{#vars}} + {{^isInherited}} + {{^isEnum}} + /// + /// {{^description}}Gets or Sets {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// {{#description}} + /// {{description}}{{/description}} + {{^conditionalSerialization}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + public {{{dataType}}} {{name}} { get; {{#isReadOnly}}private {{/isReadOnly}}set; } + + {{#isReadOnly}} + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{#conditionalSerialization}} + {{#isReadOnly}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + public {{{dataType}}} {{name}} { get; private set; } + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return false; + } + {{/isReadOnly}} + {{^isReadOnly}} + {{#isDate}} + [JsonConverter(typeof(OpenAPIDateConverter))] + {{/isDate}} + [DataMember(Name = "{{baseName}}"{{#required}}, IsRequired = true{{/required}}, EmitDefaultValue = {{#vendorExtensions.x-emit-default-value}}true{{/vendorExtensions.x-emit-default-value}}{{^vendorExtensions.x-emit-default-value}}{{#isBoolean}}true{{/isBoolean}}{{^isBoolean}}{{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{/isBoolean}}{{/vendorExtensions.x-emit-default-value}})] + public {{{dataType}}} {{name}} + { + get{ return _{{name}};} + set + { + _{{name}} = value; + _flag{{name}} = true; + } + } + private {{{dataType}}} _{{name}}; + private bool _flag{{name}}; + + /// + /// Returns false as {{name}} should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerialize{{name}}() + { + return _flag{{name}}; + } + {{/isReadOnly}} + {{/conditionalSerialization}} + {{/isEnum}} + {{/isInherited}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + {{/isAdditionalPropertiesTrue}} + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + {{#parent}} + sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); + {{/parent}} + {{#vars}} + sb.Append(" {{name}}: ").Append({{name}}).Append("\n"); + {{/vars}} + {{#isAdditionalPropertiesTrue}} + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + {{/isAdditionalPropertiesTrue}} + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public {{#parent}}{{^isArray}}{{^isMap}}override {{/isMap}}{{/isArray}}{{/parent}}{{^parent}}virtual {{/parent}}string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return {{#vars}}{{#parent}}base.Equals(input) && {{/parent}}{{^isContainer}} + ( + this.{{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}} + (this.{{name}} != null && + this.{{name}}.Equals(input.{{name}})) + {{/vendorExtensions.x-is-value-type}} + {{#vendorExtensions.x-is-value-type}} + this.{{name}}.Equals(input.{{name}}) + {{/vendorExtensions.x-is-value-type}} + ){{^-last}} && {{/-last}}{{/isContainer}}{{#isContainer}} + ( + this.{{name}} == input.{{name}} || + {{^vendorExtensions.x-is-value-type}}this.{{name}} != null && + input.{{name}} != null && + {{/vendorExtensions.x-is-value-type}}this.{{name}}.SequenceEqual(input.{{name}}) + ){{^-last}} && {{/-last}}{{/isContainer}}{{/vars}}{{^vars}}{{#parent}}base.Equals(input){{/parent}}{{^parent}}false{{/parent}}{{/vars}}{{^isAdditionalPropertiesTrue}};{{/isAdditionalPropertiesTrue}} + {{#isAdditionalPropertiesTrue}} + && (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); + {{/isAdditionalPropertiesTrue}} + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + {{#parent}} + int hashCode = base.GetHashCode(); + {{/parent}} + {{^parent}} + int hashCode = 41; + {{/parent}} + {{#vars}} + {{^vendorExtensions.x-is-value-type}} + if (this.{{name}} != null) + hashCode = hashCode * 59 + this.{{name}}.GetHashCode(); + {{/vendorExtensions.x-is-value-type}} + {{#vendorExtensions.x-is-value-type}} + hashCode = hashCode * 59 + this.{{name}}.GetHashCode(); + {{/vendorExtensions.x-is-value-type}} + {{/vars}} + {{#isAdditionalPropertiesTrue}} + if (this.AdditionalProperties != null) + hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); + {{/isAdditionalPropertiesTrue}} + return hashCode; + } + } + +{{#validatable}} +{{#discriminator}} + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + return this.BaseValidate(validationContext); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + protected IEnumerable BaseValidate(ValidationContext validationContext) + { +{{/discriminator}} +{{^discriminator}} + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { +{{/discriminator}} + {{#parent}} + {{^isArray}} + {{^isMap}} + foreach(var x in BaseValidate(validationContext)) yield return x; + {{/isMap}} + {{/isArray}} + {{/parent}} + {{#vars}} + {{#hasValidation}} + {{^isEnum}} + {{#maxLength}} + // {{{name}}} ({{{dataType}}}) maxLength + if(this.{{{name}}} != null && this.{{{name}}}.Length > {{maxLength}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be less than {{maxLength}}.", new [] { "{{{name}}}" }); + } + + {{/maxLength}} + {{#minLength}} + // {{{name}}} ({{{dataType}}}) minLength + if(this.{{{name}}} != null && this.{{{name}}}.Length < {{minLength}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, length must be greater than {{minLength}}.", new [] { "{{{name}}}" }); + } + + {{/minLength}} + {{#maximum}} + // {{{name}}} ({{{dataType}}}) maximum + if(this.{{{name}}} > ({{{dataType}}}){{maximum}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must be a value less than or equal to {{maximum}}.", new [] { "{{{name}}}" }); + } + + {{/maximum}} + {{#minimum}} + // {{{name}}} ({{{dataType}}}) minimum + if(this.{{{name}}} < ({{{dataType}}}){{minimum}}) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must be a value greater than or equal to {{minimum}}.", new [] { "{{{name}}}" }); + } + + {{/minimum}} + {{#pattern}} + {{^isByteArray}} + // {{{name}}} ({{{dataType}}}) pattern + Regex regex{{{name}}} = new Regex(@"{{{vendorExtensions.x-regex}}}"{{#vendorExtensions.x-modifiers}}{{#-first}}, {{/-first}}RegexOptions.{{{.}}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}); + if (false == regex{{{name}}}.Match(this.{{{name}}}).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must match a pattern of " + regex{{{name}}}, new [] { "{{{name}}}" }); + } + + {{/isByteArray}} + {{/pattern}} + {{/isEnum}} + {{/hasValidation}} + {{/vars}} + yield break; + } +{{/validatable}} + } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelInnerEnum.mustache new file mode 100644 index 00000000000..d9e96dccdb3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelInnerEnum.mustache @@ -0,0 +1,26 @@ + {{^isContainer}} + /// + /// {{^description}}Defines {{{name}}}{{/description}}{{#description}}{{description}}{{/description}} + /// + {{#description}} + /// {{description}} + {{/description}} + {{#isString}} + [JsonConverter(typeof(StringEnumConverter))] + {{/isString}} + {{>visibility}} enum {{#datatypeWithEnum}}{{.}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#vendorExtensions.x-enum-byte}}: byte{{/vendorExtensions.x-enum-byte}} + { + {{#allowableValues}} + {{#enumVars}} + /// + /// Enum {{name}} for value: {{{value}}} + /// + {{#isString}} + [EnumMember(Value = "{{{value}}}")] + {{/isString}} + {{name}}{{^isString}} = {{{value}}}{{/isString}}{{#isString}} = {{-index}}{{/isString}}{{^-last}},{{/-last}} + + {{/enumVars}} + {{/allowableValues}} + } + {{/isContainer}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelOneOf.mustache new file mode 100644 index 00000000000..d2d6e28b3f9 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/modelOneOf.mustache @@ -0,0 +1,264 @@ + /// + /// {{#description}}{{.}}{{/description}}{{^description}}{{classname}}{{/description}} + /// + [JsonConverter(typeof({{classname}}JsonConverter))] + [DataContract(Name = "{{{name}}}")] + {{>visibility}} partial class {{classname}} : AbstractOpenAPISchema, {{#parent}}{{{parent}}}, {{/parent}}IEquatable<{{classname}}>{{#validatable}}, IValidatableObject{{/validatable}} + { + {{#isNullable}} + /// + /// Initializes a new instance of the class. + /// + public {{classname}}() + { + this.IsNullable = true; + this.SchemaType= "oneOf"; + } + + {{/isNullable}} + {{#oneOf}} + /// + /// Initializes a new instance of the class + /// with the class + /// + /// An instance of {{{.}}}. + public {{classname}}({{{.}}} actualInstance) + { + this.IsNullable = {{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}; + this.SchemaType= "oneOf"; + this.ActualInstance = actualInstance{{^isNullable}} ?? throw new ArgumentException("Invalid instance found. Must not be null."){{/isNullable}}; + } + + {{/oneOf}} + + private Object _actualInstance; + + /// + /// Gets or Sets ActualInstance + /// + public override Object ActualInstance + { + get + { + return _actualInstance; + } + set + { + {{#oneOf}} + {{^-first}}else {{/-first}}if (value.GetType() == typeof({{{.}}})) + { + this._actualInstance = value; + } + {{/oneOf}} + else + { + throw new ArgumentException("Invalid instance found. Must be the following types:{{#oneOf}} {{{.}}}{{^-last}},{{/-last}}{{/oneOf}}"); + } + } + } + {{#oneOf}} + + /// + /// Get the actual instance of `{{{.}}}`. If the actual instanct is not `{{{.}}}`, + /// the InvalidClassException will be thrown + /// + /// An instance of {{{.}}} + public {{{.}}} Get{{{.}}}() + { + return ({{{.}}})this.ActualInstance; + } + {{/oneOf}} + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class {{classname}} {\n"); + sb.Append(" ActualInstance: ").Append(this.ActualInstance).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public override string ToJson() + { + return JsonConvert.SerializeObject(this.ActualInstance, {{classname}}.SerializerSettings); + } + + /// + /// Converts the JSON string into an instance of {{classname}} + /// + /// JSON string + /// An instance of {{classname}} + public static {{classname}} FromJson(string jsonString) + { + {{classname}} new{{classname}} = null; + + if (jsonString == null) + { + return new{{classname}}; + } + {{#useOneOfDiscriminatorLookup}} + {{#discriminator}} + + string discriminatorValue = JObject.Parse(jsonString)["{{{propertyBaseName}}}"].ToString(); + switch (discriminatorValue) + { + {{#mappedModels}} + case "{{{mappingName}}}": + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{modelName}}}>(jsonString, {{classname}}.AdditionalPropertiesSerializerSettings)); + return new{{classname}}; + {{/mappedModels}} + default: + System.Diagnostics.Debug.WriteLine(string.Format("Failed to lookup discriminator value `{0}` for {{classname}}. Possible values:{{#mappedModels}} {{{mappingName}}}{{/mappedModels}}", discriminatorValue)); + break; + } + + {{/discriminator}} + {{/useOneOfDiscriminatorLookup}} + int match = 0; + List matchedTypes = new List(); + {{#oneOf}} + + try + { + // if it does not contains "AdditionalProperties", use SerializerSettings to deserialize + if (typeof({{{.}}}).GetProperty("AdditionalProperties") == null) + { + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.SerializerSettings)); + } + else + { + new{{classname}} = new {{classname}}(JsonConvert.DeserializeObject<{{{.}}}>(jsonString, {{classname}}.AdditionalPropertiesSerializerSettings)); + } + matchedTypes.Add("{{{.}}}"); + match++; + } + catch (Exception exception) + { + // deserialization failed, try the next one + System.Diagnostics.Debug.WriteLine(string.Format("Failed to deserialize `{0}` into {{{.}}}: {1}", jsonString, exception.ToString())); + } + {{/oneOf}} + + if (match == 0) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` cannot be deserialized into any schema defined."); + } + else if (match > 1) + { + throw new InvalidDataException("The JSON string `" + jsonString + "` incorrectly matches more than one schema (should be exactly one match): " + matchedTypes); + } + + // deserialization is considered successful at this point if no exception has been thrown. + return new{{classname}}; + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input as {{classname}}).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + return this.Equals(input as {{classname}}); + {{/useCompareNetObjects}} + } + + /// + /// Returns true if {{classname}} instances are equal + /// + /// Instance of {{classname}} to be compared + /// Boolean + public bool Equals({{classname}} input) + { + {{#useCompareNetObjects}} + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + {{/useCompareNetObjects}} + {{^useCompareNetObjects}} + if (input == null) + return false; + + return this.ActualInstance.Equals(input.ActualInstance); + {{/useCompareNetObjects}} + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.ActualInstance != null) + hashCode = hashCode * 59 + this.ActualInstance.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// Custom JSON converter for {{classname}} + /// + public class {{classname}}JsonConverter : JsonConverter + { + /// + /// To write the JSON string + /// + /// JSON writer + /// Object to be converted into a JSON string + /// JSON Serializer + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + writer.WriteRawValue((string)(typeof({{classname}}).GetMethod("ToJson").Invoke(value, null))); + } + + /// + /// To convert a JSON string into an object + /// + /// JSON reader + /// Object type + /// Existing value + /// JSON Serializer + /// The object converted from the JSON string + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if(reader.TokenType != JsonToken.Null) + { + return {{classname}}.FromJson(JObject.Load(reader).ToString(Formatting.None)); + } + return null; + } + + /// + /// Check if the object can be converted + /// + /// Object type + /// True if the object can be converted + public override bool CanConvert(Type objectType) + { + return false; + } + } diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_doc.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_doc.mustache new file mode 100644 index 00000000000..babf25481c4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_doc.mustache @@ -0,0 +1,22 @@ +{{#models}} +{{#model}} +# {{{packageName}}}.{{modelPackage}}.{{{classname}}} +{{#description}}{{&description}} +{{/description}} + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#parent}} +{{#parentVars}} +**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/parentVars}} +{{/parent}} +{{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} +{{/vars}} + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_test.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_test.mustache new file mode 100644 index 00000000000..b4aefe51005 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/model_test.mustache @@ -0,0 +1,81 @@ +{{>partial_header}} + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using {{packageName}}.{{apiPackage}}; +using {{packageName}}.{{modelPackage}}; +using {{packageName}}.Client; +using System.Reflection; +using Newtonsoft.Json; + +{{#models}} +{{#model}} +namespace {{packageName}}.Test.Model +{ + /// + /// Class for testing {{classname}} + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class {{classname}}Tests : IDisposable + { + // TODO uncomment below to declare an instance variable for {{classname}} + //private {{classname}} instance; + + public {{classname}}Tests() + { + // TODO uncomment below to create an instance of {{classname}} + //instance = new {{classname}}(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of {{classname}} + /// + [Fact] + public void {{classname}}InstanceTest() + { + // TODO uncomment below to test "IsType" {{classname}} + //Assert.IsType<{{classname}}>(instance); + } + + {{#discriminator}} + {{#children}} + /// + /// Test deserialize a {{classname}} from type {{parent}} + /// + [Fact] + public void {{classname}}DeserializeFrom{{parent}}Test() + { + // TODO uncomment below to test deserialize a {{classname}} from type {{parent}} + //Assert.IsType<{{parent}}>(JsonConvert.DeserializeObject<{{parent}}>(new {{classname}}().ToJson())); + } + {{/children}} + {{/discriminator}} + + {{#vars}} + /// + /// Test the property '{{name}}' + /// + [Fact] + public void {{name}}Test() + { + // TODO unit test for the property '{{name}}' + } + {{/vars}} + + } + +} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_project.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_project.mustache new file mode 100644 index 00000000000..4f29dcf3d34 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_project.mustache @@ -0,0 +1,44 @@ + + + + false + {{targetFramework}} + {{packageName}} + {{packageName}} + Library + {{packageAuthors}} + {{packageCompany}} + {{packageTitle}} + {{packageDescription}} + {{packageCopyright}} + {{packageName}} + {{packageVersion}} + bin\$(Configuration)\$(TargetFramework)\{{packageName}}.xml{{#licenseId}} + {{licenseId}}{{/licenseId}} + https://{{{gitHost}}}/{{{gitUserId}}}/{{{gitRepoId}}}.git + git{{#releaseNote}} + {{releaseNote}}{{/releaseNote}}{{#packageTags}} + {{{packageTags}}}{{/packageTags}} + {{#nullableReferenceTypes}} + annotations + {{/nullableReferenceTypes}} + + + + {{#useCompareNetObjects}} + + {{/useCompareNetObjects}} + + + {{#useRestSharp}} + + {{/useRestSharp}} + {{#supportsRetry}} + + {{/supportsRetry}} + {{#validatable}} + + {{/validatable}} + + + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_testproject.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_testproject.mustache new file mode 100644 index 00000000000..b20a94c76c1 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/netcore_testproject.mustache @@ -0,0 +1,20 @@ + + + + {{testPackageName}} + {{testPackageName}} + {{testTargetFramework}} + false + + + + + + + + + + + + + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/nuspec.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/nuspec.mustache new file mode 100644 index 00000000000..66254acffd4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/nuspec.mustache @@ -0,0 +1,52 @@ + + + + + $id$ + {{packageTitle}} + + + $version$ + + + $author$ + + + $author$ + false + false + + + {{packageDescription}} + {{#termsOfService}} + {{termsOfService}} + {{/termsOfService}} + {{#licenseUrl}} + {{licenseUrl}} + {{/licenseUrl}} + + + + + + + {{#useCompareNetObjects}} + + {{/useCompareNetObjects}} + + {{#validatable}} + + {{/validatable}} + + + + + + + + + + + diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/partial_header.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/partial_header.mustache new file mode 100644 index 00000000000..755e937d23b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/partial_header.mustache @@ -0,0 +1,17 @@ +/* + {{#appName}} + * {{{appName}}} + * + {{/appName}} + {{#appDescription}} + * {{{appDescription}}} + * + {{/appDescription}} + {{#version}} + * The version of the OpenAPI document: {{{version}}} + {{/version}} + {{#infoEmail}} + * Contact: {{{infoEmail}}} + {{/infoEmail}} + * Generated by: https://github.com/openapitools/openapi-generator.git + */ diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/pathParam.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/pathParam.mustache new file mode 100644 index 00000000000..e8767cac94c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/pathParam.mustache @@ -0,0 +1 @@ +{{#isPathParam}}{{#pattern}}[RegularExpression("{{{pattern}}}")]{{/pattern}}{{#minLength}}{{#maxLength}}[StringLength({{maxLength}}, MinimumLength={{minLength}})]{{/maxLength}}{{/minLength}}{{#minLength}}{{^maxLength}} [MinLength({{minLength}})]{{/maxLength}}{{/minLength}}{{^minLength}}{{#maxLength}} [MaxLength({{maxLength}})]{{/maxLength}}{{/minLength}}{{#minimum}}{{#maximum}}[Range({{minimum}}, {{maximum}})]{{/maximum}}{{/minimum}}{{&dataType}} {{paramName}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/project.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/project.mustache new file mode 100644 index 00000000000..d5d3017c216 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/project.mustache @@ -0,0 +1,12 @@ +{ + "supports": {}, + "dependencies": { + "FubarCoder.RestSharp.Portable.Core": "4.0.7", + "FubarCoder.RestSharp.Portable.HttpClient": "4.0.7", + "Newtonsoft.Json": "10.0.3", + "JsonSubTypes": "1.2.0" + }, + "frameworks": { + "netstandard1.3": {} + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp-netcore-functions/visibility.mustache b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/visibility.mustache new file mode 100644 index 00000000000..a1d1f4163d4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp-netcore-functions/visibility.mustache @@ -0,0 +1 @@ +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp-netcore-functions/CsharpNetcoreFunctionsServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp-netcore-functions/CsharpNetcoreFunctionsServerCodegenTest.java new file mode 100644 index 00000000000..a62b73e7fae --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharp-netcore-functions/CsharpNetcoreFunctionsServerCodegenTest.java @@ -0,0 +1,40 @@ +/* + * Copyright 2020 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * 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. + */ + +package org.openapitools.codegen.CsharpNetcoreFunctionsServerCodegen; + +import org.openapitools.codegen.languages.CsharpNetcoreFunctionsServerCodegen; +import org.testng.Assert; +import org.testng.annotations.Test; + +public class CsharpNetcoreFunctionsServerCodegenTest { + + @Test + public void testToEnumVarName() throws Exception { + final CsharpNetcoreFunctionsServerCodegen codegen = new CsharpNetcoreFunctionsServerCodegen(); + codegen.processOpts(); + + Assert.assertEquals(codegen.toEnumVarName("FooBar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("fooBar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("foo-bar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("foo_bar", "string"), "FooBar"); + Assert.assertEquals(codegen.toEnumVarName("foo bar", "string"), "FooBar"); + + // The below cases do not work currently, camelize doesn't support uppercase + // Assert.assertEquals(codegen.toEnumVarName("FOO-BAR", "string"), "FooBar"); + // Assert.assertEquals(codegen.toEnumVarName("FOO_BAR", "string"), "FooBar"); + } +} From 15f45711a8e39f19c0166829485fc7d8a45b73df Mon Sep 17 00:00:00 2001 From: Jarrod Parkes Date: Sat, 4 Dec 2021 00:05:51 -0500 Subject: [PATCH 50/61] add swift5 option for generating frozen enums (#11013) * add swift5 option for generating frozen enums * use case unknownDefault to avoid conflicts * update comments to reflect unknownDefault case * set default values for unknown case to avoid conflict * dont need vendor extensions to detect enum raw data type * move CaseIterableDefaultsLast into models mustache template * comment catch all case and add support for other types * add frozen enums to ci pipeline * remove extraneous edit to extensions template * remove left over protocols files * small comment and case adjustments --- bin/configs/swift5-frozenEnums.yaml | 12 + docs/generators/swift5.md | 1 + .../languages/Swift5ClientCodegen.java | 16 + .../src/main/resources/swift5/Models.mustache | 22 + .../main/resources/swift5/modelEnum.mustache | 27 +- .../modelInlineEnumDeclaration.mustache | 30 +- .../options/Swift5OptionsProvider.java | 2 + .../codegen/swift5/Swift5OptionsTest.java | 1 + pom.xml | 1 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../petstore/swift5/frozenEnums/.gitignore | 105 +++ .../frozenEnums/.openapi-generator-ignore | 23 + .../frozenEnums/.openapi-generator/FILES | 110 +++ .../frozenEnums/.openapi-generator/VERSION | 1 + .../petstore/swift5/frozenEnums/Cartfile | 1 + .../swift5/frozenEnums/Package.resolved | 16 + .../petstore/swift5/frozenEnums/Package.swift | 33 + .../swift5/frozenEnums/PetstoreClient.podspec | 15 + .../Classes/OpenAPIs/APIHelper.swift | 86 +++ .../Classes/OpenAPIs/APIs.swift | 72 ++ .../OpenAPIs/APIs/AnotherFakeAPI.swift | 58 ++ .../Classes/OpenAPIs/APIs/FakeAPI.swift | 699 ++++++++++++++++++ .../APIs/FakeClassnameTags123API.swift | 61 ++ .../Classes/OpenAPIs/APIs/PetAPI.swift | 495 +++++++++++++ .../Classes/OpenAPIs/APIs/StoreAPI.swift | 196 +++++ .../Classes/OpenAPIs/APIs/UserAPI.swift | 377 ++++++++++ .../Classes/OpenAPIs/CodableHelper.swift | 49 ++ .../Classes/OpenAPIs/Configuration.swift | 15 + .../Classes/OpenAPIs/Extensions.swift | 158 ++++ .../Classes/OpenAPIs/JSONDataEncoding.swift | 53 ++ .../Classes/OpenAPIs/JSONEncodingHelper.swift | 45 ++ .../Classes/OpenAPIs/Models.swift | 80 ++ .../Models/AdditionalPropertiesClass.swift | 36 + .../Classes/OpenAPIs/Models/Animal.swift | 36 + .../Classes/OpenAPIs/Models/AnimalFarm.swift | 13 + .../Classes/OpenAPIs/Models/ApiResponse.swift | 40 + .../Models/ArrayOfArrayOfNumberOnly.swift | 32 + .../OpenAPIs/Models/ArrayOfNumberOnly.swift | 32 + .../Classes/OpenAPIs/Models/ArrayTest.swift | 40 + .../OpenAPIs/Models/Capitalization.swift | 53 ++ .../Classes/OpenAPIs/Models/Cat.swift | 40 + .../Classes/OpenAPIs/Models/CatAllOf.swift | 32 + .../Classes/OpenAPIs/Models/Category.swift | 36 + .../Classes/OpenAPIs/Models/ClassModel.swift | 33 + .../Classes/OpenAPIs/Models/Client.swift | 32 + .../Classes/OpenAPIs/Models/Dog.swift | 40 + .../Classes/OpenAPIs/Models/DogAllOf.swift | 32 + .../Classes/OpenAPIs/Models/EnumArrays.swift | 54 ++ .../Classes/OpenAPIs/Models/EnumClass.swift | 22 + .../Classes/OpenAPIs/Models/EnumTest.swift | 96 +++ .../Classes/OpenAPIs/Models/File.swift | 34 + .../OpenAPIs/Models/FileSchemaTestClass.swift | 36 + .../Classes/OpenAPIs/Models/FormatTest.swift | 80 ++ .../OpenAPIs/Models/HasOnlyReadOnly.swift | 36 + .../Classes/OpenAPIs/Models/List.swift | 32 + .../Classes/OpenAPIs/Models/MapTest.swift | 53 ++ ...opertiesAndAdditionalPropertiesClass.swift | 40 + .../OpenAPIs/Models/Model200Response.swift | 37 + .../Classes/OpenAPIs/Models/Name.swift | 45 ++ .../Classes/OpenAPIs/Models/NumberOnly.swift | 32 + .../Classes/OpenAPIs/Models/Order.swift | 63 ++ .../OpenAPIs/Models/OuterComposite.swift | 40 + .../Classes/OpenAPIs/Models/OuterEnum.swift | 22 + .../Classes/OpenAPIs/Models/Pet.swift | 63 ++ .../OpenAPIs/Models/ReadOnlyFirst.swift | 36 + .../Classes/OpenAPIs/Models/Return.swift | 33 + .../OpenAPIs/Models/SpecialModelName.swift | 32 + .../OpenAPIs/Models/StringBooleanMap.swift | 52 ++ .../Classes/OpenAPIs/Models/Tag.swift | 36 + .../OpenAPIs/Models/TypeHolderDefault.swift | 48 ++ .../OpenAPIs/Models/TypeHolderExample.swift | 48 ++ .../Classes/OpenAPIs/Models/User.swift | 61 ++ .../OpenAPIs/OpenISO8601DateFormatter.swift | 44 ++ .../OpenAPIs/SynchronizedDictionary.swift | 36 + .../OpenAPIs/URLSessionImplementations.swift | 609 +++++++++++++++ .../petstore/swift5/frozenEnums/README.md | 141 ++++ .../docs/AdditionalPropertiesClass.md | 11 + .../swift5/frozenEnums/docs/Animal.md | 11 + .../swift5/frozenEnums/docs/AnimalFarm.md | 9 + .../swift5/frozenEnums/docs/AnotherFakeAPI.md | 59 ++ .../swift5/frozenEnums/docs/ApiResponse.md | 12 + .../docs/ArrayOfArrayOfNumberOnly.md | 10 + .../frozenEnums/docs/ArrayOfNumberOnly.md | 10 + .../swift5/frozenEnums/docs/ArrayTest.md | 12 + .../swift5/frozenEnums/docs/Capitalization.md | 15 + .../petstore/swift5/frozenEnums/docs/Cat.md | 10 + .../swift5/frozenEnums/docs/CatAllOf.md | 10 + .../swift5/frozenEnums/docs/Category.md | 11 + .../swift5/frozenEnums/docs/ClassModel.md | 10 + .../swift5/frozenEnums/docs/Client.md | 10 + .../petstore/swift5/frozenEnums/docs/Dog.md | 10 + .../swift5/frozenEnums/docs/DogAllOf.md | 10 + .../swift5/frozenEnums/docs/EnumArrays.md | 11 + .../swift5/frozenEnums/docs/EnumClass.md | 9 + .../swift5/frozenEnums/docs/EnumTest.md | 14 + .../swift5/frozenEnums/docs/FakeAPI.md | 662 +++++++++++++++++ .../docs/FakeClassnameTags123API.md | 59 ++ .../petstore/swift5/frozenEnums/docs/File.md | 10 + .../frozenEnums/docs/FileSchemaTestClass.md | 11 + .../swift5/frozenEnums/docs/FormatTest.md | 22 + .../frozenEnums/docs/HasOnlyReadOnly.md | 11 + .../petstore/swift5/frozenEnums/docs/List.md | 10 + .../swift5/frozenEnums/docs/MapTest.md | 13 + ...dPropertiesAndAdditionalPropertiesClass.md | 12 + .../frozenEnums/docs/Model200Response.md | 11 + .../petstore/swift5/frozenEnums/docs/Name.md | 13 + .../swift5/frozenEnums/docs/NumberOnly.md | 10 + .../petstore/swift5/frozenEnums/docs/Order.md | 15 + .../swift5/frozenEnums/docs/OuterComposite.md | 12 + .../swift5/frozenEnums/docs/OuterEnum.md | 9 + .../petstore/swift5/frozenEnums/docs/Pet.md | 15 + .../swift5/frozenEnums/docs/PetAPI.md | 469 ++++++++++++ .../swift5/frozenEnums/docs/ReadOnlyFirst.md | 11 + .../swift5/frozenEnums/docs/Return.md | 10 + .../frozenEnums/docs/SpecialModelName.md | 10 + .../swift5/frozenEnums/docs/StoreAPI.md | 206 ++++++ .../frozenEnums/docs/StringBooleanMap.md | 9 + .../petstore/swift5/frozenEnums/docs/Tag.md | 11 + .../frozenEnums/docs/TypeHolderDefault.md | 14 + .../frozenEnums/docs/TypeHolderExample.md | 14 + .../petstore/swift5/frozenEnums/docs/User.md | 17 + .../swift5/frozenEnums/docs/UserAPI.md | 406 ++++++++++ .../petstore/swift5/frozenEnums/git_push.sh | 57 ++ .../petstore/swift5/frozenEnums/pom.xml | 43 ++ .../petstore/swift5/frozenEnums/project.yml | 15 + .../swift5/frozenEnums/run_spmbuild.sh | 3 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + .../client/petstore/swift5/swift5_test_all.sh | 1 + .../Sources/PetstoreClient/Models.swift | 22 + .../Classes/OpenAPIs/Models.swift | 22 + 140 files changed, 8099 insertions(+), 2 deletions(-) create mode 100644 bin/configs/swift5-frozenEnums.yaml create mode 100644 samples/client/petstore/swift5/frozenEnums/.gitignore create mode 100644 samples/client/petstore/swift5/frozenEnums/.openapi-generator-ignore create mode 100644 samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES create mode 100644 samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION create mode 100644 samples/client/petstore/swift5/frozenEnums/Cartfile create mode 100644 samples/client/petstore/swift5/frozenEnums/Package.resolved create mode 100644 samples/client/petstore/swift5/frozenEnums/Package.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient.podspec create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Category.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Client.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/File.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/List.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Name.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Order.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Return.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/User.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift create mode 100644 samples/client/petstore/swift5/frozenEnums/README.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/AdditionalPropertiesClass.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Animal.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/AnimalFarm.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/AnotherFakeAPI.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/ApiResponse.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/ArrayOfArrayOfNumberOnly.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/ArrayOfNumberOnly.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/ArrayTest.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Capitalization.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Cat.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/CatAllOf.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Category.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/ClassModel.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Client.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Dog.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/DogAllOf.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/EnumArrays.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/EnumClass.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/EnumTest.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/FakeAPI.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/FakeClassnameTags123API.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/File.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/FileSchemaTestClass.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/FormatTest.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/HasOnlyReadOnly.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/List.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/MapTest.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/MixedPropertiesAndAdditionalPropertiesClass.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Model200Response.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Name.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/NumberOnly.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Order.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/OuterComposite.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/OuterEnum.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Pet.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/PetAPI.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/ReadOnlyFirst.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Return.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/SpecialModelName.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/StoreAPI.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/StringBooleanMap.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/Tag.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/TypeHolderDefault.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/TypeHolderExample.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/User.md create mode 100644 samples/client/petstore/swift5/frozenEnums/docs/UserAPI.md create mode 100644 samples/client/petstore/swift5/frozenEnums/git_push.sh create mode 100644 samples/client/petstore/swift5/frozenEnums/pom.xml create mode 100644 samples/client/petstore/swift5/frozenEnums/project.yml create mode 100755 samples/client/petstore/swift5/frozenEnums/run_spmbuild.sh diff --git a/bin/configs/swift5-frozenEnums.yaml b/bin/configs/swift5-frozenEnums.yaml new file mode 100644 index 00000000000..64dc04a4f81 --- /dev/null +++ b/bin/configs/swift5-frozenEnums.yaml @@ -0,0 +1,12 @@ +generatorName: swift5 +outputDir: samples/client/petstore/swift5/frozenEnums +inputSpec: modules/openapi-generator/src/test/resources/2_0/swift/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/swift5 +generateAliasAsModel: true +additionalProperties: + podAuthors: "" + podSummary: PetstoreClient + sortParamsByRequiredFlag: false + generateFrozenEnums: false + projectName: PetstoreClient + podHomepage: https://github.com/openapitools/openapi-generator diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index e74a239be25..ddcb3bc3db0 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -11,6 +11,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |apiNamePrefix|Prefix that will be appended to all API names ('tags'). Default: empty string. e.g. Pet => Pet.| |null| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|generateFrozenEnums|Generate model enums that are "frozen". A frozen enum strictly represents the cases described in the spec, and nothing else. A non-frozen enum includes an unknown case that can represent future cases not yet described in the spec. (default: true)| |true| |generateModelAdditionalProperties|Generate model additional properties (default: true)| |true| |hashableModels|Make hashable models (default: true)| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java index 31614ac9b65..2cd6ebd8dd4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java @@ -66,6 +66,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig public static final String SWIFT_PACKAGE_PATH = "swiftPackagePath"; public static final String USE_CLASSES = "useClasses"; public static final String USE_BACKTICK_ESCAPES = "useBacktickEscapes"; + public static final String GENERATE_FROZEN_ENUMS = "generateFrozenEnums"; public static final String GENERATE_MODEL_ADDITIONAL_PROPERTIES = "generateModelAdditionalProperties"; public static final String HASHABLE_MODELS = "hashableModels"; public static final String MAP_FILE_BINARY_TO_DATA = "mapFileBinaryToData"; @@ -90,6 +91,7 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig protected boolean useClasses = false; protected boolean useBacktickEscapes = false; protected boolean generateModelAdditionalProperties = true; + protected boolean generateFrozenEnums = true; protected boolean hashableModels = true; protected boolean mapFileBinaryToData = false; protected String[] responseAs = new String[0]; @@ -281,6 +283,9 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig cliOptions.add(new CliOption(USE_BACKTICK_ESCAPES, "Escape reserved words using backticks (default: false)") .defaultValue(Boolean.FALSE.toString())); + cliOptions.add(new CliOption(GENERATE_FROZEN_ENUMS, + "Generate frozen enums (default: true)") + .defaultValue(Boolean.TRUE.toString())); cliOptions.add(new CliOption(GENERATE_MODEL_ADDITIONAL_PROPERTIES, "Generate model additional properties (default: true)") .defaultValue(Boolean.TRUE.toString())); @@ -485,6 +490,13 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig setUseBacktickEscapes(convertPropertyToBooleanAndWriteBack(USE_BACKTICK_ESCAPES)); } + // Setup generateFrozenEnums option. If true, enums will strictly include + // cases matching the spec. If false, enums will also include an extra catch-all case. + if (additionalProperties.containsKey(GENERATE_FROZEN_ENUMS)) { + setGenerateFrozenEnums(convertPropertyToBooleanAndWriteBack(GENERATE_FROZEN_ENUMS)); + } + additionalProperties.put(GENERATE_FROZEN_ENUMS, generateFrozenEnums); + if (additionalProperties.containsKey(GENERATE_MODEL_ADDITIONAL_PROPERTIES)) { setGenerateModelAdditionalProperties(convertPropertyToBooleanAndWriteBack(GENERATE_MODEL_ADDITIONAL_PROPERTIES)); } @@ -943,6 +955,10 @@ public class Swift5ClientCodegen extends DefaultCodegen implements CodegenConfig this.useBacktickEscapes = useBacktickEscapes; } + public void setGenerateFrozenEnums(boolean generateFrozenEnums) { + this.generateFrozenEnums = generateFrozenEnums; + } + public void setGenerateModelAdditionalProperties(boolean generateModelAdditionalProperties) { this.generateModelAdditionalProperties = generateModelAdditionalProperties; } diff --git a/modules/openapi-generator/src/main/resources/swift5/Models.mustache b/modules/openapi-generator/src/main/resources/swift5/Models.mustache index 3b2c5eafce1..1195d5ea9c4 100644 --- a/modules/openapi-generator/src/main/resources/swift5/Models.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/Models.mustache @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache b/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache index 4d868682a1e..08f7bf9ee40 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelEnum.mustache @@ -1,7 +1,32 @@ -{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{dataType}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable { +{{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{classname}}: {{dataType}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable{{^generateFrozenEnums}}{{#isInteger}}, CaseIterableDefaultsLast{{/isInteger}}{{#isFloat}}, CaseIterableDefaultsLast{{/isFloat}}{{#isDouble}}, CaseIterableDefaultsLast{{/isDouble}}{{#isString}}, CaseIterableDefaultsLast{{/isString}}{{/generateFrozenEnums}} { {{#allowableValues}} {{#enumVars}} case {{{name}}} = {{{value}}} {{/enumVars}} {{/allowableValues}} +{{^generateFrozenEnums}} + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. +{{#isString}} + case unknownDefaultOpenAPI = "unknown_default_open_api" +{{/isString}} +{{#isNumeric}} + // + // 192, used to calculate the raw value, was the Swift Evolution proposal for + // frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // +{{/isNumeric}} +{{#isInteger}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 +{{/isInteger}} +{{#isDouble}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 +{{/isDouble}} +{{#isFloat}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 +{{/isFloat}} +{{/generateFrozenEnums}} } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache b/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache index 039bae3cb73..1dd9c55b16f 100644 --- a/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/modelInlineEnumDeclaration.mustache @@ -1,7 +1,35 @@ - {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable { + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum {{enumName}}: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}, {{#useVapor}}Content, Hashable{{/useVapor}}{{^useVapor}}Codable{{/useVapor}}, CaseIterable{{^generateFrozenEnums}}{{#isInteger}}, CaseIterableDefaultsLast{{/isInteger}}{{#isFloat}}, CaseIterableDefaultsLast{{/isFloat}}{{#isDouble}}, CaseIterableDefaultsLast{{/isDouble}}{{#isString}}, CaseIterableDefaultsLast{{/isString}}{{#isContainer}}, CaseIterableDefaultsLast{{/isContainer}}{{/generateFrozenEnums}} { {{#allowableValues}} {{#enumVars}} case {{{name}}} = {{{value}}} {{/enumVars}} {{/allowableValues}} + {{^generateFrozenEnums}} + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + {{#isString}} + case unknownDefaultOpenAPI = "unknown_default_open_api" + {{/isString}} + {{#isContainer}} + case unknownDefaultOpenAPI = "unknown_default_open_api" + {{/isContainer}} + {{#isNumeric}} + // + // 192, used to calculate the raw value, was the Swift Evolution proposal for + // frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // + {{/isNumeric}} + {{#isInteger}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + {{/isInteger}} + {{#isDouble}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + {{/isDouble}} + {{#isFloat}} + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + {{/isFloat}} + {{/generateFrozenEnums}} } \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java index cf6b8ba3bfa..4df5b89d5ba 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/Swift5OptionsProvider.java @@ -48,6 +48,7 @@ public class Swift5OptionsProvider implements OptionsProvider { public static final String REMOVE_MIGRATION_PROJECT_NAME_CLASS_VALUE = "false"; public static final String SWIFT_USE_API_NAMESPACE_VALUE = "swiftUseApiNamespace"; public static final String USE_BACKTICKS_ESCAPES_VALUE = "false"; + public static final String GENERATE_FROZEN_ENUMS_VALUE = "true"; public static final String GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE = "true"; public static final String HASHABLE_MODELS_VALUE = "true"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; @@ -95,6 +96,7 @@ public class Swift5OptionsProvider implements OptionsProvider { .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true") .put(Swift5ClientCodegen.USE_SPM_FILE_STRUCTURE, USE_SPM_FILE_STRUCTURE_VALUE) .put(Swift5ClientCodegen.SWIFT_PACKAGE_PATH, SWIFT_PACKAGE_PATH_VALUE) + .put(Swift5ClientCodegen.GENERATE_FROZEN_ENUMS, GENERATE_FROZEN_ENUMS_VALUE) .put(Swift5ClientCodegen.GENERATE_MODEL_ADDITIONAL_PROPERTIES, GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE) .put(Swift5ClientCodegen.HASHABLE_MODELS, HASHABLE_MODELS_VALUE) .put(Swift5ClientCodegen.MAP_FILE_BINARY_TO_DATA, "false") diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java index 15a06885bc0..0550f03de29 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/swift5/Swift5OptionsTest.java @@ -49,6 +49,7 @@ public class Swift5OptionsTest extends AbstractOptionsTest { verify(clientCodegen).setPrependFormOrBodyParameters(Boolean.valueOf(Swift5OptionsProvider.PREPEND_FORM_OR_BODY_PARAMETERS_VALUE)); verify(clientCodegen).setReadonlyProperties(Boolean.parseBoolean(Swift5OptionsProvider.READONLY_PROPERTIES_VALUE)); verify(clientCodegen).setRemoveMigrationProjectNameClass(Boolean.parseBoolean(Swift5OptionsProvider.REMOVE_MIGRATION_PROJECT_NAME_CLASS_VALUE)); + verify(clientCodegen).setGenerateFrozenEnums(Boolean.parseBoolean(Swift5OptionsProvider.GENERATE_FROZEN_ENUMS_VALUE)); verify(clientCodegen).setGenerateModelAdditionalProperties(Boolean.parseBoolean(Swift5OptionsProvider.GENERATE_MODEL_ADDITIONAL_PROPERTIES_VALUE)); verify(clientCodegen).setHashableModels(Boolean.parseBoolean(Swift5OptionsProvider.HASHABLE_MODELS_VALUE)); } diff --git a/pom.xml b/pom.xml index bc359854717..d55abd2e50d 100644 --- a/pom.xml +++ b/pom.xml @@ -1434,6 +1434,7 @@ samples/client/petstore/swift5/combineLibrary samples/client/petstore/swift5/default samples/client/petstore/swift5/deprecated + samples/client/petstore/swift5/frozenEnums samples/client/petstore/swift5/nonPublicApi samples/client/petstore/swift5/objcCompatible samples/client/petstore/swift5/promisekitLibrary diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/frozenEnums/.gitignore b/samples/client/petstore/swift5/frozenEnums/.gitignore new file mode 100644 index 00000000000..627d360a903 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/.gitignore @@ -0,0 +1,105 @@ +# Created by https://www.toptal.com/developers/gitignore/api/swift,xcode +# Edit at https://www.toptal.com/developers/gitignore?templates=swift,xcode + +### Swift ### +# Xcode +# +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + +## User settings +xcuserdata/ + +## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) +*.xcscmblueprint +*.xccheckout + +## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) +build/ +DerivedData/ +*.moved-aside +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 + +## Obj-C/Swift specific +*.hmap + +## App packaging +*.ipa +*.dSYM.zip +*.dSYM + +## Playgrounds +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. +# Packages/ +# Package.pins +# Package.resolved +# *.xcodeproj +# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata +# hence it is not needed unless you have added a package configuration file to your project +# .swiftpm + +.build/ + +# CocoaPods +# We recommend against adding the Pods directory to your .gitignore. However +# you should judge for yourself, the pros and cons are mentioned at: +# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control +# Pods/ +# Add this line if you want to avoid checking in source code from the Xcode workspace +# *.xcworkspace + +# Carthage +# Add this line if you want to avoid checking in source code from Carthage dependencies. +# Carthage/Checkouts + +Carthage/Build/ + +# Add this lines if you are using Accio dependency management (Deprecated since Xcode 12) +# Dependencies/ +# .accio/ + +# fastlane +# It is recommended to not store the screenshots in the git repo. +# Instead, use fastlane to re-generate the screenshots whenever they are needed. +# For more information about the recommended setup visit: +# https://docs.fastlane.tools/best-practices/source-control/#source-control + +fastlane/report.xml +fastlane/Preview.html +fastlane/screenshots/**/*.png +fastlane/test_output + +# Code Injection +# After new code Injection tools there's a generated folder /iOSInjectionProject +# https://github.com/johnno1962/injectionforxcode + +iOSInjectionProject/ + +### Xcode ### +# Xcode +# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore + + + + +## Gcc Patch +/*.gcno + +### Xcode Patch ### +*.xcodeproj/* +!*.xcodeproj/project.pbxproj +!*.xcodeproj/xcshareddata/ +!*.xcworkspace/contents.xcworkspacedata +**/xcshareddata/WorkspaceSettings.xcsettings + +# End of https://www.toptal.com/developers/gitignore/api/swift,xcode diff --git a/samples/client/petstore/swift5/frozenEnums/.openapi-generator-ignore b/samples/client/petstore/swift5/frozenEnums/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES new file mode 100644 index 00000000000..c81943baf2a --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/FILES @@ -0,0 +1,110 @@ +.gitignore +Cartfile +Package.swift +PetstoreClient.podspec +PetstoreClient/Classes/OpenAPIs/APIHelper.swift +PetstoreClient/Classes/OpenAPIs/APIs.swift +PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +PetstoreClient/Classes/OpenAPIs/CodableHelper.swift +PetstoreClient/Classes/OpenAPIs/Configuration.swift +PetstoreClient/Classes/OpenAPIs/Extensions.swift +PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift +PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift +PetstoreClient/Classes/OpenAPIs/Models.swift +PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift +PetstoreClient/Classes/OpenAPIs/Models/Animal.swift +PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift +PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift +PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift +PetstoreClient/Classes/OpenAPIs/Models/Cat.swift +PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift +PetstoreClient/Classes/OpenAPIs/Models/Category.swift +PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift +PetstoreClient/Classes/OpenAPIs/Models/Client.swift +PetstoreClient/Classes/OpenAPIs/Models/Dog.swift +PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift +PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift +PetstoreClient/Classes/OpenAPIs/Models/File.swift +PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift +PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift +PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/List.swift +PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift +PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift +PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift +PetstoreClient/Classes/OpenAPIs/Models/Name.swift +PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift +PetstoreClient/Classes/OpenAPIs/Models/Order.swift +PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift +PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +PetstoreClient/Classes/OpenAPIs/Models/Pet.swift +PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift +PetstoreClient/Classes/OpenAPIs/Models/Return.swift +PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift +PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift +PetstoreClient/Classes/OpenAPIs/Models/Tag.swift +PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift +PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift +PetstoreClient/Classes/OpenAPIs/Models/User.swift +PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift +PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift +PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +README.md +docs/AdditionalPropertiesClass.md +docs/Animal.md +docs/AnimalFarm.md +docs/AnotherFakeAPI.md +docs/ApiResponse.md +docs/ArrayOfArrayOfNumberOnly.md +docs/ArrayOfNumberOnly.md +docs/ArrayTest.md +docs/Capitalization.md +docs/Cat.md +docs/CatAllOf.md +docs/Category.md +docs/ClassModel.md +docs/Client.md +docs/Dog.md +docs/DogAllOf.md +docs/EnumArrays.md +docs/EnumClass.md +docs/EnumTest.md +docs/FakeAPI.md +docs/FakeClassnameTags123API.md +docs/File.md +docs/FileSchemaTestClass.md +docs/FormatTest.md +docs/HasOnlyReadOnly.md +docs/List.md +docs/MapTest.md +docs/MixedPropertiesAndAdditionalPropertiesClass.md +docs/Model200Response.md +docs/Name.md +docs/NumberOnly.md +docs/Order.md +docs/OuterComposite.md +docs/OuterEnum.md +docs/Pet.md +docs/PetAPI.md +docs/ReadOnlyFirst.md +docs/Return.md +docs/SpecialModelName.md +docs/StoreAPI.md +docs/StringBooleanMap.md +docs/Tag.md +docs/TypeHolderDefault.md +docs/TypeHolderExample.md +docs/User.md +docs/UserAPI.md +git_push.sh +project.yml diff --git a/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION new file mode 100644 index 00000000000..4077803655c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/frozenEnums/Cartfile b/samples/client/petstore/swift5/frozenEnums/Cartfile new file mode 100644 index 00000000000..3f7e6304cab --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/Cartfile @@ -0,0 +1 @@ +github "Flight-School/AnyCodable" ~> 0.6.1 diff --git a/samples/client/petstore/swift5/frozenEnums/Package.resolved b/samples/client/petstore/swift5/frozenEnums/Package.resolved new file mode 100644 index 00000000000..730957420e1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/Package.resolved @@ -0,0 +1,16 @@ +{ + "object": { + "pins": [ + { + "package": "AnyCodable", + "repositoryURL": "https://github.com/Flight-School/AnyCodable", + "state": { + "branch": null, + "revision": "b1a7a8a6186f2fcb28f7bda67cfc545de48b3c80", + "version": "0.6.2" + } + } + ] + }, + "version": 1 +} diff --git a/samples/client/petstore/swift5/frozenEnums/Package.swift b/samples/client/petstore/swift5/frozenEnums/Package.swift new file mode 100644 index 00000000000..87bb775fb72 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/Package.swift @@ -0,0 +1,33 @@ +// swift-tools-version:5.1 + +import PackageDescription + +let package = Package( + name: "PetstoreClient", + platforms: [ + .iOS(.v9), + .macOS(.v10_11), + .tvOS(.v9), + .watchOS(.v3), + ], + products: [ + // Products define the executables and libraries produced by a package, and make them visible to other packages. + .library( + name: "PetstoreClient", + targets: ["PetstoreClient"] + ), + ], + dependencies: [ + // Dependencies declare other packages that this package depends on. + .package(url: "https://github.com/Flight-School/AnyCodable", from: "0.6.1"), + ], + targets: [ + // Targets are the basic building blocks of a package. A target can define a module or a test suite. + // Targets can depend on other targets in this package, and on products in packages which this package depends on. + .target( + name: "PetstoreClient", + dependencies: ["AnyCodable", ], + path: "PetstoreClient/Classes" + ), + ] +) diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient.podspec b/samples/client/petstore/swift5/frozenEnums/PetstoreClient.podspec new file mode 100644 index 00000000000..0e6bf7ec024 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient.podspec @@ -0,0 +1,15 @@ +Pod::Spec.new do |s| + s.name = 'PetstoreClient' + s.ios.deployment_target = '9.0' + s.osx.deployment_target = '10.11' + s.tvos.deployment_target = '9.0' + s.watchos.deployment_target = '3.0' + s.version = '1.0.0' + s.source = { :git => 'git@github.com:OpenAPITools/openapi-generator.git', :tag => 'v1.0.0' } + s.authors = '' + s.license = 'Proprietary' + s.homepage = 'https://github.com/openapitools/openapi-generator' + s.summary = 'PetstoreClient' + s.source_files = 'PetstoreClient/Classes/**/*.swift' + s.dependency 'AnyCodable-FlightSchool', '~> 0.6.1' +end diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift new file mode 100644 index 00000000000..049b7f655f1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIHelper.swift @@ -0,0 +1,86 @@ +// APIHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct APIHelper { + public static func rejectNil(_ source: [String: Any?]) -> [String: Any]? { + let destination = source.reduce(into: [String: Any]()) { result, item in + if let value = item.value { + result[item.key] = value + } + } + + if destination.isEmpty { + return nil + } + return destination + } + + public static func rejectNilHeaders(_ source: [String: Any?]) -> [String: String] { + return source.reduce(into: [String: String]()) { result, item in + if let collection = item.value as? [Any?] { + result[item.key] = collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") + } else if let value: Any = item.value { + result[item.key] = "\(value)" + } + } + } + + public static func convertBoolToString(_ source: [String: Any]?) -> [String: Any]? { + guard let source = source else { + return nil + } + + return source.reduce(into: [String: Any]()) { result, item in + switch item.value { + case let x as Bool: + result[item.key] = x.description + default: + result[item.key] = item.value + } + } + } + + public static func mapValueToPathItem(_ source: Any) -> Any { + if let collection = source as? [Any?] { + return collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .joined(separator: ",") + } + return source + } + + public static func mapValuesToQueryItems(_ source: [String: Any?]) -> [URLQueryItem]? { + let destination = source.filter { $0.value != nil }.reduce(into: [URLQueryItem]()) { result, item in + if let collection = item.value as? [Any?] { + collection + .compactMap { value in + guard let value = value else { return nil } + return "\(value)" + } + .forEach { value in + result.append(URLQueryItem(name: item.key, value: value)) + } + } else if let value = item.value { + result.append(URLQueryItem(name: item.key, value: "\(value)")) + } + } + + if destination.isEmpty { + return nil + } + return destination + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift new file mode 100644 index 00000000000..a7933c418ad --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs.swift @@ -0,0 +1,72 @@ +// APIs.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +// We reverted the change of PetstoreClientAPI to PetstoreClient introduced in https://github.com/OpenAPITools/openapi-generator/pull/9624 +// Because it was causing the following issue https://github.com/OpenAPITools/openapi-generator/issues/9953 +// If you are affected by this issue, please consider removing the following two lines, +// By setting the option removeMigrationProjectNameClass to true in the generator +@available(*, deprecated, renamed: "PetstoreClientAPI") +public typealias PetstoreClient = PetstoreClientAPI + +open class PetstoreClientAPI { + public static var basePath = "http://petstore.swagger.io:80/v2" + public static var customHeaders: [String: String] = [:] + public static var credential: URLCredential? + public static var requestBuilderFactory: RequestBuilderFactory = URLSessionRequestBuilderFactory() + public static var apiResponseQueue: DispatchQueue = .main +} + +open class RequestBuilder { + var credential: URLCredential? + var headers: [String: String] + public let parameters: [String: Any]? + public let method: String + public let URLString: String + + /// Optional block to obtain a reference to the request's progress instance when available. + /// With the URLSession http client the request's progress only works on iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0. + /// If you need to get the request's progress in older OS versions, please use Alamofire http client. + public var onProgressReady: ((Progress) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + self.method = method + self.URLString = URLString + self.parameters = parameters + self.headers = headers + + addHeaders(PetstoreClientAPI.customHeaders) + } + + open func addHeaders(_ aHeaders: [String: String]) { + for (header, value) in aHeaders { + headers[header] = value + } + } + + @discardableResult + open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> URLSessionTask? { + return nil + } + + public func addHeader(name: String, value: String) -> Self { + if !value.isEmpty { + headers[name] = value + } + return self + } + + open func addCredential() -> Self { + credential = PetstoreClientAPI.credential + return self + } +} + +public protocol RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type + func getBuilder() -> RequestBuilder.Type +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift new file mode 100644 index 00000000000..ac45c1f454b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -0,0 +1,58 @@ +// +// AnotherFakeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class AnotherFakeAPI { + + /** + To test special tags + + - parameter body: (body) client model + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func call123testSpecialTags(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) -> URLSessionTask? { + return call123testSpecialTagsWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test special tags + - PATCH /another-fake/dummy + - To test special tags and operation ID starting with number + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func call123testSpecialTagsWithRequestBuilder(body: Client) -> RequestBuilder { + let localVariablePath = "/another-fake/dummy" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift new file mode 100644 index 00000000000..9f5c7a495e1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -0,0 +1,699 @@ +// +// FakeAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class FakeAPI { + + /** + + - parameter body: (body) Input boolean as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func fakeOuterBooleanSerialize(body: Bool? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Bool?, _ error: Error?) -> Void)) -> URLSessionTask? { + return fakeOuterBooleanSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/boolean + - Test serialization of outer boolean types + - parameter body: (body) Input boolean as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterBooleanSerializeWithRequestBuilder(body: Bool? = nil) -> RequestBuilder { + let localVariablePath = "/fake/outer/boolean" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter body: (body) Input composite as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: OuterComposite?, _ error: Error?) -> Void)) -> URLSessionTask? { + return fakeOuterCompositeSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/composite + - Test serialization of object with outer number type + - parameter body: (body) Input composite as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterCompositeSerializeWithRequestBuilder(body: OuterComposite? = nil) -> RequestBuilder { + let localVariablePath = "/fake/outer/composite" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter body: (body) Input number as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func fakeOuterNumberSerialize(body: Double? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Double?, _ error: Error?) -> Void)) -> URLSessionTask? { + return fakeOuterNumberSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/number + - Test serialization of outer number types + - parameter body: (body) Input number as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterNumberSerializeWithRequestBuilder(body: Double? = nil) -> RequestBuilder { + let localVariablePath = "/fake/outer/number" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter body: (body) Input string as post body (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func fakeOuterStringSerialize(body: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) -> URLSessionTask? { + return fakeOuterStringSerializeWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - POST /fake/outer/string + - Test serialization of outer string types + - parameter body: (body) Input string as post body (optional) + - returns: RequestBuilder + */ + open class func fakeOuterStringSerializeWithRequestBuilder(body: String? = nil) -> RequestBuilder { + let localVariablePath = "/fake/outer/string" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter body: (body) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testBodyWithFileSchema(body: FileSchemaTestClass, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testBodyWithFileSchemaWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - PUT /fake/body-with-file-schema + - For this test, the body for this request much reference a schema named `File`. + - parameter body: (body) + - returns: RequestBuilder + */ + open class func testBodyWithFileSchemaWithRequestBuilder(body: FileSchemaTestClass) -> RequestBuilder { + let localVariablePath = "/fake/body-with-file-schema" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + + - parameter query: (query) + - parameter body: (body) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testBodyWithQueryParams(query: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testBodyWithQueryParamsWithRequestBuilder(query: query, body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + - PUT /fake/body-with-query-params + - parameter query: (query) + - parameter body: (body) + - returns: RequestBuilder + */ + open class func testBodyWithQueryParamsWithRequestBuilder(query: String, body: User) -> RequestBuilder { + let localVariablePath = "/fake/body-with-query-params" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "query": query.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + To test \"client\" model + + - parameter body: (body) client model + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testClientModel(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testClientModelWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test \"client\" model + - PATCH /fake + - To test \"client\" model + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func testClientModelWithRequestBuilder(body: Client) -> RequestBuilder { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter number: (form) None + - parameter float: (form) None (optional) + - parameter double: (form) None + - parameter string: (form) None (optional) + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testEndpointParametersWithRequestBuilder(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - POST /fake + - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + - BASIC: + - type: http + - name: http_basic_test + - parameter integer: (form) None (optional) + - parameter int32: (form) None (optional) + - parameter int64: (form) None (optional) + - parameter number: (form) None + - parameter float: (form) None (optional) + - parameter double: (form) None + - parameter string: (form) None (optional) + - parameter patternWithoutDelimiter: (form) None + - parameter byte: (form) None + - parameter binary: (form) None (optional) + - parameter date: (form) None (optional) + - parameter dateTime: (form) None (optional) + - parameter password: (form) None (optional) + - parameter callback: (form) None (optional) + - returns: RequestBuilder + */ + open class func testEndpointParametersWithRequestBuilder(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil) -> RequestBuilder { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "integer": integer?.encodeToJSON(), + "int32": int32?.encodeToJSON(), + "int64": int64?.encodeToJSON(), + "number": number.encodeToJSON(), + "float": float?.encodeToJSON(), + "double": double.encodeToJSON(), + "string": string?.encodeToJSON(), + "pattern_without_delimiter": patternWithoutDelimiter.encodeToJSON(), + "byte": byte.encodeToJSON(), + "binary": binary?.encodeToJSON(), + "date": date?.encodeToJSON(), + "dateTime": dateTime?.encodeToJSON(), + "password": password?.encodeToJSON(), + "callback": callback?.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + * enum for parameter enumHeaderStringArray + */ + public enum EnumHeaderStringArray_testEnumParameters: String, CaseIterable { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumHeaderString + */ + public enum EnumHeaderString_testEnumParameters: String, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryStringArray + */ + public enum EnumQueryStringArray_testEnumParameters: String, CaseIterable { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumQueryString + */ + public enum EnumQueryString_testEnumParameters: String, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + * enum for parameter enumQueryInteger + */ + public enum EnumQueryInteger_testEnumParameters: Int, CaseIterable { + case _1 = 1 + case number2 = -2 + } + + /** + * enum for parameter enumQueryDouble + */ + public enum EnumQueryDouble_testEnumParameters: Double, CaseIterable { + case _11 = 1.1 + case number12 = -1.2 + } + + /** + * enum for parameter enumFormStringArray + */ + public enum EnumFormStringArray_testEnumParameters: String, CaseIterable { + case greaterThan = ">" + case dollar = "$" + } + + /** + * enum for parameter enumFormString + */ + public enum EnumFormString_testEnumParameters: String, CaseIterable { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + } + + /** + To test enum parameters + + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional) + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testEnumParametersWithRequestBuilder(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test enum parameters + - GET /fake + - To test enum parameters + - parameter enumHeaderStringArray: (header) Header parameter enum test (string array) (optional) + - parameter enumHeaderString: (header) Header parameter enum test (string) (optional, default to .efg) + - parameter enumQueryStringArray: (query) Query parameter enum test (string array) (optional) + - parameter enumQueryString: (query) Query parameter enum test (string) (optional, default to .efg) + - parameter enumQueryInteger: (query) Query parameter enum test (double) (optional) + - parameter enumQueryDouble: (query) Query parameter enum test (double) (optional) + - parameter enumFormStringArray: (form) Form parameter enum test (string array) (optional, default to .dollar) + - parameter enumFormString: (form) Form parameter enum test (string) (optional, default to .efg) + - returns: RequestBuilder + */ + open class func testEnumParametersWithRequestBuilder(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil) -> RequestBuilder { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "enum_form_string_array": enumFormStringArray?.encodeToJSON(), + "enum_form_string": enumFormString?.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "enum_query_string_array": enumQueryStringArray?.encodeToJSON(), + "enum_query_string": enumQueryString?.encodeToJSON(), + "enum_query_integer": enumQueryInteger?.encodeToJSON(), + "enum_query_double": enumQueryDouble?.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + "enum_header_string_array": enumHeaderStringArray?.encodeToJSON(), + "enum_header_string": enumHeaderString?.encodeToJSON(), + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Fake endpoint to test group parameters (optional) + + - parameter requiredStringGroup: (query) Required String in group parameters + - parameter requiredBooleanGroup: (header) Required Boolean in group parameters + - parameter requiredInt64Group: (query) Required Integer in group parameters + - parameter stringGroup: (query) String in group parameters (optional) + - parameter booleanGroup: (header) Boolean in group parameters (optional) + - parameter int64Group: (query) Integer in group parameters (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testGroupParametersWithRequestBuilder(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Fake endpoint to test group parameters (optional) + - DELETE /fake + - Fake endpoint to test group parameters (optional) + - parameter requiredStringGroup: (query) Required String in group parameters + - parameter requiredBooleanGroup: (header) Required Boolean in group parameters + - parameter requiredInt64Group: (query) Required Integer in group parameters + - parameter stringGroup: (query) String in group parameters (optional) + - parameter booleanGroup: (header) Boolean in group parameters (optional) + - parameter int64Group: (query) Integer in group parameters (optional) + - returns: RequestBuilder + */ + open class func testGroupParametersWithRequestBuilder(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil) -> RequestBuilder { + let localVariablePath = "/fake" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "required_string_group": requiredStringGroup.encodeToJSON(), + "required_int64_group": requiredInt64Group.encodeToJSON(), + "string_group": stringGroup?.encodeToJSON(), + "int64_group": int64Group?.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + "required_boolean_group": requiredBooleanGroup.encodeToJSON(), + "boolean_group": booleanGroup?.encodeToJSON(), + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + test inline additionalProperties + + - parameter param: (body) request body + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testInlineAdditionalProperties(param: [String: String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testInlineAdditionalPropertiesWithRequestBuilder(param: param).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + test inline additionalProperties + - POST /fake/inline-additionalProperties + - parameter param: (body) request body + - returns: RequestBuilder + */ + open class func testInlineAdditionalPropertiesWithRequestBuilder(param: [String: String]) -> RequestBuilder { + let localVariablePath = "/fake/inline-additionalProperties" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: param) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + test json serialization of form data + + - parameter param: (form) field1 + - parameter param2: (form) field2 + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testJsonFormData(param: String, param2: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testJsonFormDataWithRequestBuilder(param: param, param2: param2).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + test json serialization of form data + - GET /fake/jsonFormData + - parameter param: (form) field1 + - parameter param2: (form) field2 + - returns: RequestBuilder + */ + open class func testJsonFormDataWithRequestBuilder(param: String, param2: String) -> RequestBuilder { + let localVariablePath = "/fake/jsonFormData" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "param": param.encodeToJSON(), + "param2": param2.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift new file mode 100644 index 00000000000..ac274a7c550 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -0,0 +1,61 @@ +// +// FakeClassnameTags123API.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class FakeClassnameTags123API { + + /** + To test class name in snake case + + - parameter body: (body) client model + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func testClassname(body: Client, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Client?, _ error: Error?) -> Void)) -> URLSessionTask? { + return testClassnameWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + To test class name in snake case + - PATCH /fake_classname_test + - To test class name in snake case + - API Key: + - type: apiKey api_key_query (QUERY) + - name: api_key_query + - parameter body: (body) client model + - returns: RequestBuilder + */ + open class func testClassnameWithRequestBuilder(body: Client) -> RequestBuilder { + let localVariablePath = "/fake_classname_test" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "PATCH", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift new file mode 100644 index 00000000000..2baca7e644a --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -0,0 +1,495 @@ +// +// PetAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class PetAPI { + + /** + Add a new pet to the store + + - parameter body: (body) Pet object that needs to be added to the store + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func addPet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return addPetWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Add a new pet to the store + - POST /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: RequestBuilder + */ + open class func addPetWithRequestBuilder(body: Pet) -> RequestBuilder { + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Deletes a pet + + - parameter apiKey: (header) (optional) + - parameter petId: (path) Pet id to delete + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func deletePet(apiKey: String? = nil, petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return deletePetWithRequestBuilder(apiKey: apiKey, petId: petId).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Deletes a pet + - DELETE /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter apiKey: (header) (optional) + - parameter petId: (path) Pet id to delete + - returns: RequestBuilder + */ + open class func deletePetWithRequestBuilder(apiKey: String? = nil, petId: Int64) -> RequestBuilder { + var localVariablePath = "/pet/{petId}" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "api_key": apiKey?.encodeToJSON(), + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + * enum for parameter status + */ + public enum Status_findPetsByStatus: String, CaseIterable { + case available = "available" + case pending = "pending" + case sold = "sold" + } + + /** + Finds Pets by status + + - parameter status: (query) Status values that need to be considered for filter + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func findPetsByStatus(status: [Status_findPetsByStatus], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + return findPetsByStatusWithRequestBuilder(status: status).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Finds Pets by status + - GET /pet/findByStatus + - Multiple status values can be provided with comma separated strings + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter status: (query) Status values that need to be considered for filter + - returns: RequestBuilder<[Pet]> + */ + open class func findPetsByStatusWithRequestBuilder(status: [Status_findPetsByStatus]) -> RequestBuilder<[Pet]> { + let localVariablePath = "/pet/findByStatus" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "status": status.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Finds Pets by tags + + - parameter tags: (query) Tags to filter by + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @available(*, deprecated, message: "This operation is deprecated.") + @discardableResult + open class func findPetsByTags(tags: [String], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [Pet]?, _ error: Error?) -> Void)) -> URLSessionTask? { + return findPetsByTagsWithRequestBuilder(tags: tags).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Finds Pets by tags + - GET /pet/findByTags + - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter tags: (query) Tags to filter by + - returns: RequestBuilder<[Pet]> + */ + @available(*, deprecated, message: "This operation is deprecated.") + open class func findPetsByTagsWithRequestBuilder(tags: [String]) -> RequestBuilder<[Pet]> { + let localVariablePath = "/pet/findByTags" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "tags": tags.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder<[Pet]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Find pet by ID + + - parameter petId: (path) ID of pet to return + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func getPetById(petId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Pet?, _ error: Error?) -> Void)) -> URLSessionTask? { + return getPetByIdWithRequestBuilder(petId: petId).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Find pet by ID + - GET /pet/{petId} + - Returns a single pet + - API Key: + - type: apiKey api_key + - name: api_key + - parameter petId: (path) ID of pet to return + - returns: RequestBuilder + */ + open class func getPetByIdWithRequestBuilder(petId: Int64) -> RequestBuilder { + var localVariablePath = "/pet/{petId}" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Update an existing pet + + - parameter body: (body) Pet object that needs to be added to the store + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func updatePet(body: Pet, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return updatePetWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Update an existing pet + - PUT /pet + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter body: (body) Pet object that needs to be added to the store + - returns: RequestBuilder + */ + open class func updatePetWithRequestBuilder(body: Pet) -> RequestBuilder { + let localVariablePath = "/pet" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Updates a pet in the store with form data + + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return updatePetWithFormWithRequestBuilder(petId: petId, name: name, status: status).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Updates a pet in the store with form data + - POST /pet/{petId} + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet that needs to be updated + - parameter name: (form) Updated name of the pet (optional) + - parameter status: (form) Updated status of the pet (optional) + - returns: RequestBuilder + */ + open class func updatePetWithFormWithRequestBuilder(petId: Int64, name: String? = nil, status: String? = nil) -> RequestBuilder { + var localVariablePath = "/pet/{petId}" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "name": name?.encodeToJSON(), + "status": status?.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/x-www-form-urlencoded", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + uploads an image + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) -> URLSessionTask? { + return uploadFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, file: file).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + uploads an image + - POST /pet/{petId}/uploadImage + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter file: (form) file to upload (optional) + - returns: RequestBuilder + */ + open class func uploadFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil) -> RequestBuilder { + var localVariablePath = "/pet/{petId}/uploadImage" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "additionalMetadata": additionalMetadata?.encodeToJSON(), + "file": file?.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + uploads an image (required) + + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter requiredFile: (form) file to upload + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: ApiResponse?, _ error: Error?) -> Void)) -> URLSessionTask? { + return uploadFileWithRequiredFileWithRequestBuilder(petId: petId, additionalMetadata: additionalMetadata, requiredFile: requiredFile).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + uploads an image (required) + - POST /fake/{petId}/uploadImageWithRequiredFile + - OAuth: + - type: oauth2 + - name: petstore_auth + - parameter petId: (path) ID of pet to update + - parameter additionalMetadata: (form) Additional data to pass to server (optional) + - parameter requiredFile: (form) file to upload + - returns: RequestBuilder + */ + open class func uploadFileWithRequiredFileWithRequestBuilder(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL) -> RequestBuilder { + var localVariablePath = "/fake/{petId}/uploadImageWithRequiredFile" + let petIdPreEscape = "\(APIHelper.mapValueToPathItem(petId))" + let petIdPostEscape = petIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{petId}", with: petIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableFormParams: [String: Any?] = [ + "additionalMetadata": additionalMetadata?.encodeToJSON(), + "requiredFile": requiredFile.encodeToJSON(), + ] + + let localVariableNonNullParameters = APIHelper.rejectNil(localVariableFormParams) + let localVariableParameters = APIHelper.convertBoolToString(localVariableNonNullParameters) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "multipart/form-data", + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift new file mode 100644 index 00000000000..f2539226866 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -0,0 +1,196 @@ +// +// StoreAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class StoreAPI { + + /** + Delete purchase order by ID + + - parameter orderId: (path) ID of the order that needs to be deleted + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func deleteOrder(orderId: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return deleteOrderWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Delete purchase order by ID + - DELETE /store/order/{order_id} + - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + - parameter orderId: (path) ID of the order that needs to be deleted + - returns: RequestBuilder + */ + open class func deleteOrderWithRequestBuilder(orderId: String) -> RequestBuilder { + var localVariablePath = "/store/order/{order_id}" + let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Returns pet inventories by status + + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func getInventory(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: [String: Int]?, _ error: Error?) -> Void)) -> URLSessionTask? { + return getInventoryWithRequestBuilder().execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Returns pet inventories by status + - GET /store/inventory + - Returns a map of status codes to quantities + - API Key: + - type: apiKey api_key + - name: api_key + - returns: RequestBuilder<[String: Int]> + */ + open class func getInventoryWithRequestBuilder() -> RequestBuilder<[String: Int]> { + let localVariablePath = "/store/inventory" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder<[String: Int]>.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Find purchase order by ID + + - parameter orderId: (path) ID of pet that needs to be fetched + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func getOrderById(orderId: Int64, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) -> URLSessionTask? { + return getOrderByIdWithRequestBuilder(orderId: orderId).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Find purchase order by ID + - GET /store/order/{order_id} + - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + - parameter orderId: (path) ID of pet that needs to be fetched + - returns: RequestBuilder + */ + open class func getOrderByIdWithRequestBuilder(orderId: Int64) -> RequestBuilder { + var localVariablePath = "/store/order/{order_id}" + let orderIdPreEscape = "\(APIHelper.mapValueToPathItem(orderId))" + let orderIdPostEscape = orderIdPreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{order_id}", with: orderIdPostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Place an order for a pet + + - parameter body: (body) order placed for purchasing the pet + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func placeOrder(body: Order, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Order?, _ error: Error?) -> Void)) -> URLSessionTask? { + return placeOrderWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Place an order for a pet + - POST /store/order + - parameter body: (body) order placed for purchasing the pet + - returns: RequestBuilder + */ + open class func placeOrderWithRequestBuilder(body: Order) -> RequestBuilder { + let localVariablePath = "/store/order" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift new file mode 100644 index 00000000000..3fc59f9ef4f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -0,0 +1,377 @@ +// +// UserAPI.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +open class UserAPI { + + /** + Create user + + - parameter body: (body) Created user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func createUser(body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return createUserWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Create user + - POST /user + - This can only be done by the logged in user. + - parameter body: (body) Created user object + - returns: RequestBuilder + */ + open class func createUserWithRequestBuilder(body: User) -> RequestBuilder { + let localVariablePath = "/user" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func createUsersWithArrayInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return createUsersWithArrayInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Creates list of users with given input array + - POST /user/createWithArray + - parameter body: (body) List of user object + - returns: RequestBuilder + */ + open class func createUsersWithArrayInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let localVariablePath = "/user/createWithArray" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Creates list of users with given input array + + - parameter body: (body) List of user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func createUsersWithListInput(body: [User], apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return createUsersWithListInputWithRequestBuilder(body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Creates list of users with given input array + - POST /user/createWithList + - parameter body: (body) List of user object + - returns: RequestBuilder + */ + open class func createUsersWithListInputWithRequestBuilder(body: [User]) -> RequestBuilder { + let localVariablePath = "/user/createWithList" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "POST", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Delete user + + - parameter username: (path) The name that needs to be deleted + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func deleteUser(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return deleteUserWithRequestBuilder(username: username).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Delete user + - DELETE /user/{username} + - This can only be done by the logged in user. + - parameter username: (path) The name that needs to be deleted + - returns: RequestBuilder + */ + open class func deleteUserWithRequestBuilder(username: String) -> RequestBuilder { + var localVariablePath = "/user/{username}" + let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "DELETE", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Get user by user name + + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func getUserByName(username: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: User?, _ error: Error?) -> Void)) -> URLSessionTask? { + return getUserByNameWithRequestBuilder(username: username).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Get user by user name + - GET /user/{username} + - parameter username: (path) The name that needs to be fetched. Use user1 for testing. + - returns: RequestBuilder + */ + open class func getUserByNameWithRequestBuilder(username: String) -> RequestBuilder { + var localVariablePath = "/user/{username}" + let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Logs user into the system + + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func loginUser(username: String, password: String, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: String?, _ error: Error?) -> Void)) -> URLSessionTask? { + return loginUserWithRequestBuilder(username: username, password: password).execute(apiResponseQueue) { result in + switch result { + case let .success(response): + completion(response.body, nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Logs user into the system + - GET /user/login + - responseHeaders: [X-Rate-Limit(Int), X-Expires-After(Date)] + - parameter username: (query) The user name for login + - parameter password: (query) The password for login in clear text + - returns: RequestBuilder + */ + open class func loginUserWithRequestBuilder(username: String, password: String) -> RequestBuilder { + let localVariablePath = "/user/login" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + var localVariableUrlComponents = URLComponents(string: localVariableURLString) + localVariableUrlComponents?.queryItems = APIHelper.mapValuesToQueryItems([ + "username": username.encodeToJSON(), + "password": password.encodeToJSON(), + ]) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Logs out current logged in user session + + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func logoutUser(apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return logoutUserWithRequestBuilder().execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Logs out current logged in user session + - GET /user/logout + - returns: RequestBuilder + */ + open class func logoutUserWithRequestBuilder() -> RequestBuilder { + let localVariablePath = "/user/logout" + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters: [String: Any]? = nil + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "GET", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } + + /** + Updated user + + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - parameter apiResponseQueue: The queue on which api response is dispatched. + - parameter completion: completion handler to receive the data and the error objects + */ + @discardableResult + open class func updateUser(username: String, body: User, apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, completion: @escaping ((_ data: Void?, _ error: Error?) -> Void)) -> URLSessionTask? { + return updateUserWithRequestBuilder(username: username, body: body).execute(apiResponseQueue) { result in + switch result { + case .success: + completion((), nil) + case let .failure(error): + completion(nil, error) + } + } + } + + /** + Updated user + - PUT /user/{username} + - This can only be done by the logged in user. + - parameter username: (path) name that need to be deleted + - parameter body: (body) Updated user object + - returns: RequestBuilder + */ + open class func updateUserWithRequestBuilder(username: String, body: User) -> RequestBuilder { + var localVariablePath = "/user/{username}" + let usernamePreEscape = "\(APIHelper.mapValueToPathItem(username))" + let usernamePostEscape = usernamePreEscape.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? "" + localVariablePath = localVariablePath.replacingOccurrences(of: "{username}", with: usernamePostEscape, options: .literal, range: nil) + let localVariableURLString = PetstoreClientAPI.basePath + localVariablePath + let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: body) + + let localVariableUrlComponents = URLComponents(string: localVariableURLString) + + let localVariableNillableHeaders: [String: Any?] = [ + : + ] + + let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) + + let localVariableRequestBuilder: RequestBuilder.Type = PetstoreClientAPI.requestBuilderFactory.getNonDecodableBuilder() + + return localVariableRequestBuilder.init(method: "PUT", URLString: (localVariableUrlComponents?.string ?? localVariableURLString), parameters: localVariableParameters, headers: localVariableHeaderParameters) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift new file mode 100644 index 00000000000..09c82e53e13 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/CodableHelper.swift @@ -0,0 +1,49 @@ +// +// CodableHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class CodableHelper { + private static var customDateFormatter: DateFormatter? + private static var defaultDateFormatter: DateFormatter = OpenISO8601DateFormatter() + + private static var customJSONDecoder: JSONDecoder? + private static var defaultJSONDecoder: JSONDecoder = { + let decoder = JSONDecoder() + decoder.dateDecodingStrategy = .formatted(CodableHelper.dateFormatter) + return decoder + }() + + private static var customJSONEncoder: JSONEncoder? + private static var defaultJSONEncoder: JSONEncoder = { + let encoder = JSONEncoder() + encoder.dateEncodingStrategy = .formatted(CodableHelper.dateFormatter) + encoder.outputFormatting = .prettyPrinted + return encoder + }() + + public static var dateFormatter: DateFormatter { + get { return customDateFormatter ?? defaultDateFormatter } + set { customDateFormatter = newValue } + } + public static var jsonDecoder: JSONDecoder { + get { return customJSONDecoder ?? defaultJSONDecoder } + set { customJSONDecoder = newValue } + } + public static var jsonEncoder: JSONEncoder { + get { return customJSONEncoder ?? defaultJSONEncoder } + set { customJSONEncoder = newValue } + } + + open class func decode(_ type: T.Type, from data: Data) -> Swift.Result where T: Decodable { + return Swift.Result { try jsonDecoder.decode(type, from: data) } + } + + open class func encode(_ value: T) -> Swift.Result where T: Encodable { + return Swift.Result { try jsonEncoder.encode(value) } + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift new file mode 100644 index 00000000000..8fb05331889 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Configuration.swift @@ -0,0 +1,15 @@ +// Configuration.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class Configuration { + + // This value is used to configure the date formatter that is used to serialize dates into JSON format. + // You must set it prior to encoding any dates, and it will only be read once. + @available(*, unavailable, message: "To set a different date format, use CodableHelper.dateFormatter instead.") + public static var dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift new file mode 100644 index 00000000000..e2b73073804 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Extensions.swift @@ -0,0 +1,158 @@ +// Extensions.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +extension Bool: JSONEncodable {} +extension Float: JSONEncodable {} +extension Int: JSONEncodable {} +extension Int32: JSONEncodable {} +extension Int64: JSONEncodable {} +extension Double: JSONEncodable {} +extension String: JSONEncodable {} +extension URL: JSONEncodable {} +extension UUID: JSONEncodable {} + +extension RawRepresentable where RawValue: JSONEncodable { + func encodeToJSON() -> Any { return self.rawValue } +} + +private func encodeIfPossible(_ object: T) -> Any { + if let encodableObject = object as? JSONEncodable { + return encodableObject.encodeToJSON() + } else { + return object + } +} + +extension Array: JSONEncodable { + func encodeToJSON() -> Any { + return self.map(encodeIfPossible) + } +} + +extension Set: JSONEncodable { + func encodeToJSON() -> Any { + return Array(self).encodeToJSON() + } +} + +extension Dictionary: JSONEncodable { + func encodeToJSON() -> Any { + var dictionary = [AnyHashable: Any]() + for (key, value) in self { + dictionary[key] = encodeIfPossible(value) + } + return dictionary + } +} + +extension Data: JSONEncodable { + func encodeToJSON() -> Any { + return self.base64EncodedString(options: Data.Base64EncodingOptions()) + } +} + +extension Date: JSONEncodable { + func encodeToJSON() -> Any { + return CodableHelper.dateFormatter.string(from: self) + } +} + +extension String: CodingKey { + + public var stringValue: String { + return self + } + + public init?(stringValue: String) { + self.init(stringLiteral: stringValue) + } + + public var intValue: Int? { + return nil + } + + public init?(intValue: Int) { + return nil + } + +} + +extension KeyedEncodingContainerProtocol { + + public mutating func encodeArray(_ values: [T], forKey key: Self.Key) throws where T: Encodable { + var arrayContainer = nestedUnkeyedContainer(forKey: key) + try arrayContainer.encode(contentsOf: values) + } + + public mutating func encodeArrayIfPresent(_ values: [T]?, forKey key: Self.Key) throws where T: Encodable { + if let values = values { + try encodeArray(values, forKey: key) + } + } + + public mutating func encodeMap(_ pairs: [Self.Key: T]) throws where T: Encodable { + for (key, value) in pairs { + try encode(value, forKey: key) + } + } + + public mutating func encodeMapIfPresent(_ pairs: [Self.Key: T]?) throws where T: Encodable { + if let pairs = pairs { + try encodeMap(pairs) + } + } + +} + +extension KeyedDecodingContainerProtocol { + + public func decodeArray(_ type: T.Type, forKey key: Self.Key) throws -> [T] where T: Decodable { + var tmpArray = [T]() + + var nestedContainer = try nestedUnkeyedContainer(forKey: key) + while !nestedContainer.isAtEnd { + let arrayValue = try nestedContainer.decode(T.self) + tmpArray.append(arrayValue) + } + + return tmpArray + } + + public func decodeArrayIfPresent(_ type: T.Type, forKey key: Self.Key) throws -> [T]? where T: Decodable { + var tmpArray: [T]? + + if contains(key) { + tmpArray = try decodeArray(T.self, forKey: key) + } + + return tmpArray + } + + public func decodeMap(_ type: T.Type, excludedKeys: Set) throws -> [Self.Key: T] where T: Decodable { + var map: [Self.Key: T] = [:] + + for key in allKeys { + if !excludedKeys.contains(key) { + let value = try decode(T.self, forKey: key) + map[key] = value + } + } + + return map + } + +} + +extension HTTPURLResponse { + var isStatusCodeSuccessful: Bool { + return (200 ..< 300).contains(statusCode) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift new file mode 100644 index 00000000000..b79e9f5e64d --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONDataEncoding.swift @@ -0,0 +1,53 @@ +// +// JSONDataEncoding.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +public struct JSONDataEncoding { + + // MARK: Properties + + private static let jsonDataKey = "jsonData" + + // MARK: Encoding + + /// Creates a URL request by encoding parameters and applying them onto an existing request. + /// + /// - parameter urlRequest: The request to have parameters applied. + /// - parameter parameters: The parameters to apply. This should have a single key/value + /// pair with "jsonData" as the key and a Data object as the value. + /// + /// - throws: An `Error` if the encoding process encounters an error. + /// + /// - returns: The encoded request. + public func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) -> URLRequest { + var urlRequest = urlRequest + + guard let jsonData = parameters?[JSONDataEncoding.jsonDataKey] as? Data, !jsonData.isEmpty else { + return urlRequest + } + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = jsonData + + return urlRequest + } + + public static func encodingParameters(jsonData: Data?) -> [String: Any]? { + var returnedParams: [String: Any]? + if let jsonData = jsonData, !jsonData.isEmpty { + var params: [String: Any] = [:] + params[jsonDataKey] = jsonData + returnedParams = params + } + return returnedParams + } + +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift new file mode 100644 index 00000000000..02f78ffb470 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/JSONEncodingHelper.swift @@ -0,0 +1,45 @@ +// +// JSONEncodingHelper.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +open class JSONEncodingHelper { + + open class func encodingParameters(forEncodableObject encodableObj: T?) -> [String: Any]? { + var params: [String: Any]? + + // Encode the Encodable object + if let encodableObj = encodableObj { + let encodeResult = CodableHelper.encode(encodableObj) + do { + let data = try encodeResult.get() + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + } + } + + return params + } + + open class func encodingParameters(forEncodableObject encodableObj: Any?) -> [String: Any]? { + var params: [String: Any]? + + if let encodableObj = encodableObj { + do { + let data = try JSONSerialization.data(withJSONObject: encodableObj, options: .prettyPrinted) + params = JSONDataEncoding.encodingParameters(jsonData: data) + } catch { + print(error.localizedDescription) + return nil + } + } + + return params + } + +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift new file mode 100644 index 00000000000..7787127c40d --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -0,0 +1,80 @@ +// Models.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +protocol JSONEncodable { + func encodeToJSON() -> Any +} + +extension JSONEncodable { + func encodeToJSON() -> Any { self } +} + +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + +public enum ErrorResponse: Error { + case error(Int, Data?, URLResponse?, Error) +} + +public enum DownloadException: Error { + case responseDataMissing + case responseFailed + case requestMissing + case requestMissingPath + case requestMissingURL +} + +public enum DecodableRequestBuilderError: Error { + case emptyDataResponse + case nilHTTPResponse + case unsuccessfulHTTPStatusCode + case jsonDecoding(DecodingError) + case generalError(Error) +} + +open class Response { + public let statusCode: Int + public let header: [String: String] + public let body: T + + public init(statusCode: Int, header: [String: String], body: T) { + self.statusCode = statusCode + self.header = header + self.body = body + } + + public convenience init(response: HTTPURLResponse, body: T) { + let rawHeader = response.allHeaderFields + var header = [String: String]() + for (key, value) in rawHeader { + if let key = key.base as? String, let value = value as? String { + header[key] = value + } + } + self.init(statusCode: response.statusCode, header: header, body: body) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift new file mode 100644 index 00000000000..621afb93561 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AdditionalPropertiesClass.swift @@ -0,0 +1,36 @@ +// +// AdditionalPropertiesClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct AdditionalPropertiesClass: Codable, Hashable { + + public var mapString: [String: String]? + public var mapMapString: [String: [String: String]]? + + public init(mapString: [String: String]? = nil, mapMapString: [String: [String: String]]? = nil) { + self.mapString = mapString + self.mapMapString = mapMapString + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case mapString = "map_string" + case mapMapString = "map_map_string" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapString, forKey: .mapString) + try container.encodeIfPresent(mapMapString, forKey: .mapMapString) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift new file mode 100644 index 00000000000..cdd4f5335b9 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Animal.swift @@ -0,0 +1,36 @@ +// +// Animal.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Animal: Codable, Hashable { + + public var className: String + public var color: String? = "red" + + public init(className: String, color: String? = "red") { + self.className = className + self.color = color + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift new file mode 100644 index 00000000000..a0b09cb9761 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/AnimalFarm.swift @@ -0,0 +1,13 @@ +// +// AnimalFarm.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public typealias AnimalFarm = [Animal] diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift new file mode 100644 index 00000000000..c365505ab9d --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ApiResponse.swift @@ -0,0 +1,40 @@ +// +// ApiResponse.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ApiResponse: Codable, Hashable { + + public var code: Int? + public var type: String? + public var message: String? + + public init(code: Int? = nil, type: String? = nil, message: String? = nil) { + self.code = code + self.type = type + self.message = message + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case code + case type + case message + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(code, forKey: .code) + try container.encodeIfPresent(type, forKey: .type) + try container.encodeIfPresent(message, forKey: .message) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift new file mode 100644 index 00000000000..226f7456181 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfArrayOfNumberOnly.swift @@ -0,0 +1,32 @@ +// +// ArrayOfArrayOfNumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ArrayOfArrayOfNumberOnly: Codable, Hashable { + + public var arrayArrayNumber: [[Double]]? + + public init(arrayArrayNumber: [[Double]]? = nil) { + self.arrayArrayNumber = arrayArrayNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayArrayNumber = "ArrayArrayNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayArrayNumber, forKey: .arrayArrayNumber) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift new file mode 100644 index 00000000000..39831127871 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayOfNumberOnly.swift @@ -0,0 +1,32 @@ +// +// ArrayOfNumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ArrayOfNumberOnly: Codable, Hashable { + + public var arrayNumber: [Double]? + + public init(arrayNumber: [Double]? = nil) { + self.arrayNumber = arrayNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayNumber = "ArrayNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayNumber, forKey: .arrayNumber) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift new file mode 100644 index 00000000000..8865d76bef2 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ArrayTest.swift @@ -0,0 +1,40 @@ +// +// ArrayTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ArrayTest: Codable, Hashable { + + public var arrayOfString: [String]? + public var arrayArrayOfInteger: [[Int64]]? + public var arrayArrayOfModel: [[ReadOnlyFirst]]? + + public init(arrayOfString: [String]? = nil, arrayArrayOfInteger: [[Int64]]? = nil, arrayArrayOfModel: [[ReadOnlyFirst]]? = nil) { + self.arrayOfString = arrayOfString + self.arrayArrayOfInteger = arrayArrayOfInteger + self.arrayArrayOfModel = arrayArrayOfModel + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case arrayOfString = "array_of_string" + case arrayArrayOfInteger = "array_array_of_integer" + case arrayArrayOfModel = "array_array_of_model" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(arrayOfString, forKey: .arrayOfString) + try container.encodeIfPresent(arrayArrayOfInteger, forKey: .arrayArrayOfInteger) + try container.encodeIfPresent(arrayArrayOfModel, forKey: .arrayArrayOfModel) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift new file mode 100644 index 00000000000..71cd93bce5f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Capitalization.swift @@ -0,0 +1,53 @@ +// +// Capitalization.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Capitalization: Codable, Hashable { + + public var smallCamel: String? + public var capitalCamel: String? + public var smallSnake: String? + public var capitalSnake: String? + public var sCAETHFlowPoints: String? + /** Name of the pet */ + public var ATT_NAME: String? + + public init(smallCamel: String? = nil, capitalCamel: String? = nil, smallSnake: String? = nil, capitalSnake: String? = nil, sCAETHFlowPoints: String? = nil, ATT_NAME: String? = nil) { + self.smallCamel = smallCamel + self.capitalCamel = capitalCamel + self.smallSnake = smallSnake + self.capitalSnake = capitalSnake + self.sCAETHFlowPoints = sCAETHFlowPoints + self.ATT_NAME = ATT_NAME + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case smallCamel + case capitalCamel = "CapitalCamel" + case smallSnake = "small_Snake" + case capitalSnake = "Capital_Snake" + case sCAETHFlowPoints = "SCA_ETH_Flow_Points" + case ATT_NAME + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(smallCamel, forKey: .smallCamel) + try container.encodeIfPresent(capitalCamel, forKey: .capitalCamel) + try container.encodeIfPresent(smallSnake, forKey: .smallSnake) + try container.encodeIfPresent(capitalSnake, forKey: .capitalSnake) + try container.encodeIfPresent(sCAETHFlowPoints, forKey: .sCAETHFlowPoints) + try container.encodeIfPresent(ATT_NAME, forKey: .ATT_NAME) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift new file mode 100644 index 00000000000..457e04bd475 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Cat.swift @@ -0,0 +1,40 @@ +// +// Cat.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Cat: Codable, Hashable { + + public var className: String + public var color: String? = "red" + public var declawed: Bool? + + public init(className: String, color: String? = "red", declawed: Bool? = nil) { + self.className = className + self.color = color + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(declawed, forKey: .declawed) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift new file mode 100644 index 00000000000..8caebb1c206 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/CatAllOf.swift @@ -0,0 +1,32 @@ +// +// CatAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct CatAllOf: Codable, Hashable { + + public var declawed: Bool? + + public init(declawed: Bool? = nil) { + self.declawed = declawed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case declawed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(declawed, forKey: .declawed) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Category.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Category.swift new file mode 100644 index 00000000000..89016ca353d --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Category.swift @@ -0,0 +1,36 @@ +// +// Category.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Category: Codable, Hashable { + + public var id: Int64? + public var name: String? = "default-name" + + public init(id: Int64? = nil, name: String? = "default-name") { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encode(name, forKey: .name) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift new file mode 100644 index 00000000000..16e69e560bd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ClassModel.swift @@ -0,0 +1,33 @@ +// +// ClassModel.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model with \"_class\" property */ +public struct ClassModel: Codable, Hashable { + + public var _class: String? + + public init(_class: String? = nil) { + self._class = _class + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _class + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_class, forKey: ._class) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Client.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Client.swift new file mode 100644 index 00000000000..60dbc5dc5c1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Client.swift @@ -0,0 +1,32 @@ +// +// Client.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Client: Codable, Hashable { + + public var client: String? + + public init(client: String? = nil) { + self.client = client + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case client + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(client, forKey: .client) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift new file mode 100644 index 00000000000..658732a7f36 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Dog.swift @@ -0,0 +1,40 @@ +// +// Dog.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Dog: Codable, Hashable { + + public var className: String + public var color: String? = "red" + public var breed: String? + + public init(className: String, color: String? = "red", breed: String? = nil) { + self.className = className + self.color = color + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case className + case color + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(className, forKey: .className) + try container.encodeIfPresent(color, forKey: .color) + try container.encodeIfPresent(breed, forKey: .breed) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift new file mode 100644 index 00000000000..82b0dedf35b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/DogAllOf.swift @@ -0,0 +1,32 @@ +// +// DogAllOf.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct DogAllOf: Codable, Hashable { + + public var breed: String? + + public init(breed: String? = nil) { + self.breed = breed + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case breed + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(breed, forKey: .breed) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift new file mode 100644 index 00000000000..321066b9f4e --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumArrays.swift @@ -0,0 +1,54 @@ +// +// EnumArrays.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct EnumArrays: Codable, Hashable { + + public enum JustSymbol: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case greaterThanOrEqualTo = ">=" + case dollar = "$" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public enum ArrayEnum: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case fish = "fish" + case crab = "crab" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public var justSymbol: JustSymbol? + public var arrayEnum: [ArrayEnum]? + + public init(justSymbol: JustSymbol? = nil, arrayEnum: [ArrayEnum]? = nil) { + self.justSymbol = justSymbol + self.arrayEnum = arrayEnum + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case justSymbol = "just_symbol" + case arrayEnum = "array_enum" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justSymbol, forKey: .justSymbol) + try container.encodeIfPresent(arrayEnum, forKey: .arrayEnum) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift new file mode 100644 index 00000000000..eef3045b291 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumClass.swift @@ -0,0 +1,22 @@ +// +// EnumClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum EnumClass: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case abc = "_abc" + case efg = "-efg" + case xyz = "(xyz)" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift new file mode 100644 index 00000000000..d6a96c72d97 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/EnumTest.swift @@ -0,0 +1,96 @@ +// +// EnumTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct EnumTest: Codable, Hashable { + + public enum EnumString: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case upper = "UPPER" + case lower = "lower" + case empty = "" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public enum EnumStringRequired: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case upper = "UPPER" + case lower = "lower" + case empty = "" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public enum EnumInteger: Int, Codable, CaseIterable, CaseIterableDefaultsLast { + case _1 = 1 + case number1 = -1 + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + // + // 192, used to calculate the raw value, was the Swift Evolution proposal for + // frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + } + public enum EnumNumber: Double, Codable, CaseIterable, CaseIterableDefaultsLast { + case _11 = 1.1 + case number12 = -1.2 + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + // + // 192, used to calculate the raw value, was the Swift Evolution proposal for + // frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // + case unknownDefaultOpenAPI = -11184809 // Int.min / 192 + } + public var enumString: EnumString? + public var enumStringRequired: EnumStringRequired + public var enumInteger: EnumInteger? + public var enumNumber: EnumNumber? + public var outerEnum: OuterEnum? + + public init(enumString: EnumString? = nil, enumStringRequired: EnumStringRequired, enumInteger: EnumInteger? = nil, enumNumber: EnumNumber? = nil, outerEnum: OuterEnum? = nil) { + self.enumString = enumString + self.enumStringRequired = enumStringRequired + self.enumInteger = enumInteger + self.enumNumber = enumNumber + self.outerEnum = outerEnum + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case enumString = "enum_string" + case enumStringRequired = "enum_string_required" + case enumInteger = "enum_integer" + case enumNumber = "enum_number" + case outerEnum + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(enumString, forKey: .enumString) + try container.encode(enumStringRequired, forKey: .enumStringRequired) + try container.encodeIfPresent(enumInteger, forKey: .enumInteger) + try container.encodeIfPresent(enumNumber, forKey: .enumNumber) + try container.encodeIfPresent(outerEnum, forKey: .outerEnum) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/File.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/File.swift new file mode 100644 index 00000000000..05dd5b1a825 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/File.swift @@ -0,0 +1,34 @@ +// +// File.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Must be named `File` for test. */ +public struct File: Codable, Hashable { + + /** Test capitalization */ + public var sourceURI: String? + + public init(sourceURI: String? = nil) { + self.sourceURI = sourceURI + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case sourceURI + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(sourceURI, forKey: .sourceURI) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift new file mode 100644 index 00000000000..3ca66a31359 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FileSchemaTestClass.swift @@ -0,0 +1,36 @@ +// +// FileSchemaTestClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct FileSchemaTestClass: Codable, Hashable { + + public var file: File? + public var files: [File]? + + public init(file: File? = nil, files: [File]? = nil) { + self.file = file + self.files = files + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case file + case files + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(file, forKey: .file) + try container.encodeIfPresent(files, forKey: .files) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift new file mode 100644 index 00000000000..a7a4b39e720 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/FormatTest.swift @@ -0,0 +1,80 @@ +// +// FormatTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct FormatTest: Codable, Hashable { + + public var integer: Int? + public var int32: Int? + public var int64: Int64? + public var number: Double + public var float: Float? + public var double: Double? + public var string: String? + public var byte: Data + public var binary: URL? + public var date: Date + public var dateTime: Date? + public var uuid: UUID? + public var password: String + + public init(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double? = nil, string: String? = nil, byte: Data, binary: URL? = nil, date: Date, dateTime: Date? = nil, uuid: UUID? = nil, password: String) { + self.integer = integer + self.int32 = int32 + self.int64 = int64 + self.number = number + self.float = float + self.double = double + self.string = string + self.byte = byte + self.binary = binary + self.date = date + self.dateTime = dateTime + self.uuid = uuid + self.password = password + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case integer + case int32 + case int64 + case number + case float + case double + case string + case byte + case binary + case date + case dateTime + case uuid + case password + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(integer, forKey: .integer) + try container.encodeIfPresent(int32, forKey: .int32) + try container.encodeIfPresent(int64, forKey: .int64) + try container.encode(number, forKey: .number) + try container.encodeIfPresent(float, forKey: .float) + try container.encodeIfPresent(double, forKey: .double) + try container.encodeIfPresent(string, forKey: .string) + try container.encode(byte, forKey: .byte) + try container.encodeIfPresent(binary, forKey: .binary) + try container.encode(date, forKey: .date) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encode(password, forKey: .password) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift new file mode 100644 index 00000000000..54ed8a723c6 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/HasOnlyReadOnly.swift @@ -0,0 +1,36 @@ +// +// HasOnlyReadOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct HasOnlyReadOnly: Codable, Hashable { + + public var bar: String? + public var foo: String? + + public init(bar: String? = nil, foo: String? = nil) { + self.bar = bar + self.foo = foo + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case foo + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(foo, forKey: .foo) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/List.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/List.swift new file mode 100644 index 00000000000..67e3048469f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/List.swift @@ -0,0 +1,32 @@ +// +// List.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct List: Codable, Hashable { + + public var _123list: String? + + public init(_123list: String? = nil) { + self._123list = _123list + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _123list = "123-list" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_123list, forKey: ._123list) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift new file mode 100644 index 00000000000..c0b5a369451 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MapTest.swift @@ -0,0 +1,53 @@ +// +// MapTest.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct MapTest: Codable, Hashable { + + public enum MapOfEnumString: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case upper = "UPPER" + case lower = "lower" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public var mapMapOfString: [String: [String: String]]? + public var mapOfEnumString: [String: String]? + public var directMap: [String: Bool]? + public var indirectMap: StringBooleanMap? + + public init(mapMapOfString: [String: [String: String]]? = nil, mapOfEnumString: [String: String]? = nil, directMap: [String: Bool]? = nil, indirectMap: StringBooleanMap? = nil) { + self.mapMapOfString = mapMapOfString + self.mapOfEnumString = mapOfEnumString + self.directMap = directMap + self.indirectMap = indirectMap + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case mapMapOfString = "map_map_of_string" + case mapOfEnumString = "map_of_enum_string" + case directMap = "direct_map" + case indirectMap = "indirect_map" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(mapMapOfString, forKey: .mapMapOfString) + try container.encodeIfPresent(mapOfEnumString, forKey: .mapOfEnumString) + try container.encodeIfPresent(directMap, forKey: .directMap) + try container.encodeIfPresent(indirectMap, forKey: .indirectMap) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift new file mode 100644 index 00000000000..c79ca459217 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/MixedPropertiesAndAdditionalPropertiesClass.swift @@ -0,0 +1,40 @@ +// +// MixedPropertiesAndAdditionalPropertiesClass.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct MixedPropertiesAndAdditionalPropertiesClass: Codable, Hashable { + + public var uuid: UUID? + public var dateTime: Date? + public var map: [String: Animal]? + + public init(uuid: UUID? = nil, dateTime: Date? = nil, map: [String: Animal]? = nil) { + self.uuid = uuid + self.dateTime = dateTime + self.map = map + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case uuid + case dateTime + case map + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(uuid, forKey: .uuid) + try container.encodeIfPresent(dateTime, forKey: .dateTime) + try container.encodeIfPresent(map, forKey: .map) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift new file mode 100644 index 00000000000..23402143f71 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Model200Response.swift @@ -0,0 +1,37 @@ +// +// Model200Response.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model name starting with number */ +public struct Model200Response: Codable, Hashable { + + public var name: Int? + public var _class: String? + + public init(name: Int? = nil, _class: String? = nil) { + self.name = name + self._class = _class + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case _class = "class" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(name, forKey: .name) + try container.encodeIfPresent(_class, forKey: ._class) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Name.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Name.swift new file mode 100644 index 00000000000..a28f46a33ce --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Name.swift @@ -0,0 +1,45 @@ +// +// Name.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing model name same as property name */ +public struct Name: Codable, Hashable { + + public var name: Int + public var snakeCase: Int? + public var property: String? + public var _123number: Int? + + public init(name: Int, snakeCase: Int? = nil, property: String? = nil, _123number: Int? = nil) { + self.name = name + self.snakeCase = snakeCase + self.property = property + self._123number = _123number + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case name + case snakeCase = "snake_case" + case property + case _123number = "123Number" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(name, forKey: .name) + try container.encodeIfPresent(snakeCase, forKey: .snakeCase) + try container.encodeIfPresent(property, forKey: .property) + try container.encodeIfPresent(_123number, forKey: ._123number) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift new file mode 100644 index 00000000000..87ceb64bb97 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/NumberOnly.swift @@ -0,0 +1,32 @@ +// +// NumberOnly.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct NumberOnly: Codable, Hashable { + + public var justNumber: Double? + + public init(justNumber: Double? = nil) { + self.justNumber = justNumber + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case justNumber = "JustNumber" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(justNumber, forKey: .justNumber) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Order.swift new file mode 100644 index 00000000000..5615d10ff4c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -0,0 +1,63 @@ +// +// Order.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Order: Codable, Hashable { + + public enum Status: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public var id: Int64? + public var petId: Int64? + public var quantity: Int? + public var shipDate: Date? + /** Order Status */ + public var status: Status? + public var complete: Bool? = false + + public init(id: Int64? = nil, petId: Int64? = nil, quantity: Int? = nil, shipDate: Date? = nil, status: Status? = nil, complete: Bool? = false) { + self.id = id + self.petId = petId + self.quantity = quantity + self.shipDate = shipDate + self.status = status + self.complete = complete + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case petId + case quantity + case shipDate + case status + case complete + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(petId, forKey: .petId) + try container.encodeIfPresent(quantity, forKey: .quantity) + try container.encodeIfPresent(shipDate, forKey: .shipDate) + try container.encodeIfPresent(status, forKey: .status) + try container.encodeIfPresent(complete, forKey: .complete) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift new file mode 100644 index 00000000000..edeaccaeaa6 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterComposite.swift @@ -0,0 +1,40 @@ +// +// OuterComposite.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct OuterComposite: Codable, Hashable { + + public var myNumber: Double? + public var myString: String? + public var myBoolean: Bool? + + public init(myNumber: Double? = nil, myString: String? = nil, myBoolean: Bool? = nil) { + self.myNumber = myNumber + self.myString = myString + self.myBoolean = myBoolean + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case myNumber = "my_number" + case myString = "my_string" + case myBoolean = "my_boolean" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(myNumber, forKey: .myNumber) + try container.encodeIfPresent(myString, forKey: .myString) + try container.encodeIfPresent(myBoolean, forKey: .myBoolean) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift new file mode 100644 index 00000000000..e418b2c445b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -0,0 +1,22 @@ +// +// OuterEnum.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public enum OuterEnum: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case placed = "placed" + case approved = "approved" + case delivered = "delivered" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift new file mode 100644 index 00000000000..81afbc4b2a1 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Pet.swift @@ -0,0 +1,63 @@ +// +// Pet.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Pet: Codable, Hashable { + + public enum Status: String, Codable, CaseIterable, CaseIterableDefaultsLast { + case available = "available" + case pending = "pending" + case sold = "sold" + // This case is a catch-all generated by OpenAPI such that the enum is "non-frozen". + // If new enum cases are added that are unknown to the spec/client, they are safely + // decoded to this case. The raw value of this case is a dummy value that attempts + // to avoids collisions with previously specified cases. + case unknownDefaultOpenAPI = "unknown_default_open_api" + } + public var id: Int64? + public var category: Category? + public var name: String + public var photoUrls: [String] + public var tags: [Tag]? + /** pet status in the store */ + public var status: Status? + + public init(id: Int64? = nil, category: Category? = nil, name: String, photoUrls: [String], tags: [Tag]? = nil, status: Status? = nil) { + self.id = id + self.category = category + self.name = name + self.photoUrls = photoUrls + self.tags = tags + self.status = status + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case category + case name + case photoUrls + case tags + case status + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(category, forKey: .category) + try container.encode(name, forKey: .name) + try container.encode(photoUrls, forKey: .photoUrls) + try container.encodeIfPresent(tags, forKey: .tags) + try container.encodeIfPresent(status, forKey: .status) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift new file mode 100644 index 00000000000..57ba3f577c8 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/ReadOnlyFirst.swift @@ -0,0 +1,36 @@ +// +// ReadOnlyFirst.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct ReadOnlyFirst: Codable, Hashable { + + public var bar: String? + public var baz: String? + + public init(bar: String? = nil, baz: String? = nil) { + self.bar = bar + self.baz = baz + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case bar + case baz + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(bar, forKey: .bar) + try container.encodeIfPresent(baz, forKey: .baz) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Return.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Return.swift new file mode 100644 index 00000000000..afc2b51f8f3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Return.swift @@ -0,0 +1,33 @@ +// +// Return.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +/** Model for testing reserved words */ +public struct Return: Codable, Hashable { + + public var _return: Int? + + public init(_return: Int? = nil) { + self._return = _return + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case _return = "return" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(_return, forKey: ._return) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift new file mode 100644 index 00000000000..bfe9723f888 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/SpecialModelName.swift @@ -0,0 +1,32 @@ +// +// SpecialModelName.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct SpecialModelName: Codable, Hashable { + + public var specialPropertyName: Int64? + + public init(specialPropertyName: Int64? = nil) { + self.specialPropertyName = specialPropertyName + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case specialPropertyName = "$special[property.name]" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(specialPropertyName, forKey: .specialPropertyName) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift new file mode 100644 index 00000000000..126c35c85a6 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/StringBooleanMap.swift @@ -0,0 +1,52 @@ +// +// StringBooleanMap.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct StringBooleanMap: Codable, Hashable { + + + public enum CodingKeys: CodingKey, CaseIterable { + } + + public var additionalProperties: [String: Bool] = [:] + + public subscript(key: String) -> Bool? { + get { + if let value = additionalProperties[key] { + return value + } + return nil + } + + set { + additionalProperties[key] = newValue + } + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + var additionalPropertiesContainer = encoder.container(keyedBy: String.self) + try additionalPropertiesContainer.encodeMap(additionalProperties) + } + + // Decodable protocol methods + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + + var nonAdditionalPropertyKeys = Set() + let additionalPropertiesContainer = try decoder.container(keyedBy: String.self) + additionalProperties = try additionalPropertiesContainer.decodeMap(Bool.self, excludedKeys: nonAdditionalPropertyKeys) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift new file mode 100644 index 00000000000..07b826264f3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/Tag.swift @@ -0,0 +1,36 @@ +// +// Tag.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct Tag: Codable, Hashable { + + public var id: Int64? + public var name: String? + + public init(id: Int64? = nil, name: String? = nil) { + self.id = id + self.name = name + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case name + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(name, forKey: .name) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift new file mode 100644 index 00000000000..e58eecd960f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderDefault.swift @@ -0,0 +1,48 @@ +// +// TypeHolderDefault.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TypeHolderDefault: Codable, Hashable { + + public var stringItem: String = "what" + public var numberItem: Double + public var integerItem: Int + public var boolItem: Bool = true + public var arrayItem: [Int] + + public init(stringItem: String = "what", numberItem: Double, integerItem: Int, boolItem: Bool = true, arrayItem: [Int]) { + self.stringItem = stringItem + self.numberItem = numberItem + self.integerItem = integerItem + self.boolItem = boolItem + self.arrayItem = arrayItem + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case stringItem = "string_item" + case numberItem = "number_item" + case integerItem = "integer_item" + case boolItem = "bool_item" + case arrayItem = "array_item" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift new file mode 100644 index 00000000000..6c22fdbae7a --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/TypeHolderExample.swift @@ -0,0 +1,48 @@ +// +// TypeHolderExample.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct TypeHolderExample: Codable, Hashable { + + public var stringItem: String + public var numberItem: Double + public var integerItem: Int + public var boolItem: Bool + public var arrayItem: [Int] + + public init(stringItem: String, numberItem: Double, integerItem: Int, boolItem: Bool, arrayItem: [Int]) { + self.stringItem = stringItem + self.numberItem = numberItem + self.integerItem = integerItem + self.boolItem = boolItem + self.arrayItem = arrayItem + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case stringItem = "string_item" + case numberItem = "number_item" + case integerItem = "integer_item" + case boolItem = "bool_item" + case arrayItem = "array_item" + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(stringItem, forKey: .stringItem) + try container.encode(numberItem, forKey: .numberItem) + try container.encode(integerItem, forKey: .integerItem) + try container.encode(boolItem, forKey: .boolItem) + try container.encode(arrayItem, forKey: .arrayItem) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/User.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/User.swift new file mode 100644 index 00000000000..7afe359ae40 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/Models/User.swift @@ -0,0 +1,61 @@ +// +// User.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if canImport(AnyCodable) +import AnyCodable +#endif + +public struct User: Codable, Hashable { + + public var id: Int64? + public var username: String? + public var firstName: String? + public var lastName: String? + public var email: String? + public var password: String? + public var phone: String? + /** User Status */ + public var userStatus: Int? + + public init(id: Int64? = nil, username: String? = nil, firstName: String? = nil, lastName: String? = nil, email: String? = nil, password: String? = nil, phone: String? = nil, userStatus: Int? = nil) { + self.id = id + self.username = username + self.firstName = firstName + self.lastName = lastName + self.email = email + self.password = password + self.phone = phone + self.userStatus = userStatus + } + + public enum CodingKeys: String, CodingKey, CaseIterable { + case id + case username + case firstName + case lastName + case email + case password + case phone + case userStatus + } + + // Encodable protocol methods + + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + try container.encodeIfPresent(username, forKey: .username) + try container.encodeIfPresent(firstName, forKey: .firstName) + try container.encodeIfPresent(lastName, forKey: .lastName) + try container.encodeIfPresent(email, forKey: .email) + try container.encodeIfPresent(password, forKey: .password) + try container.encodeIfPresent(phone, forKey: .phone) + try container.encodeIfPresent(userStatus, forKey: .userStatus) + } +} + diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift new file mode 100644 index 00000000000..e06208074cd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/OpenISO8601DateFormatter.swift @@ -0,0 +1,44 @@ +// +// OpenISO8601DateFormatter.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +// https://stackoverflow.com/a/50281094/976628 +public class OpenISO8601DateFormatter: DateFormatter { + static let withoutSeconds: DateFormatter = { + let formatter = DateFormatter() + formatter.calendar = Calendar(identifier: .iso8601) + formatter.locale = Locale(identifier: "en_US_POSIX") + formatter.timeZone = TimeZone(secondsFromGMT: 0) + formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ" + return formatter + }() + + private func setup() { + calendar = Calendar(identifier: .iso8601) + locale = Locale(identifier: "en_US_POSIX") + timeZone = TimeZone(secondsFromGMT: 0) + dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" + } + + override init() { + super.init() + setup() + } + + required init?(coder aDecoder: NSCoder) { + super.init(coder: aDecoder) + setup() + } + + override public func date(from string: String) -> Date? { + if let result = super.date(from: string) { + return result + } + return OpenISO8601DateFormatter.withoutSeconds.date(from: string) + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift new file mode 100644 index 00000000000..acf7ff4031b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/SynchronizedDictionary.swift @@ -0,0 +1,36 @@ +// SynchronizedDictionary.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation + +internal struct SynchronizedDictionary { + + private var dictionary = [K: V]() + private let queue = DispatchQueue( + label: "SynchronizedDictionary", + qos: DispatchQoS.userInitiated, + attributes: [DispatchQueue.Attributes.concurrent], + autoreleaseFrequency: DispatchQueue.AutoreleaseFrequency.inherit, + target: nil + ) + + internal subscript(key: K) -> V? { + get { + var value: V? + + queue.sync { + value = self.dictionary[key] + } + + return value + } + set { + queue.sync(flags: DispatchWorkItemFlags.barrier) { + self.dictionary[key] = newValue + } + } + } +} diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift new file mode 100644 index 00000000000..fe7fb6683bc --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -0,0 +1,609 @@ +// URLSessionImplementations.swift +// +// Generated by openapi-generator +// https://openapi-generator.tech +// + +import Foundation +#if !os(macOS) +import MobileCoreServices +#endif + +class URLSessionRequestBuilderFactory: RequestBuilderFactory { + func getNonDecodableBuilder() -> RequestBuilder.Type { + return URLSessionRequestBuilder.self + } + + func getBuilder() -> RequestBuilder.Type { + return URLSessionDecodableRequestBuilder.self + } +} + +public typealias PetstoreClientAPIChallengeHandler = ((URLSession, URLSessionTask, URLAuthenticationChallenge) -> (URLSession.AuthChallengeDisposition, URLCredential?)) + +// Store the URLSession's delegate to retain its reference +private let sessionDelegate = SessionDelegate() + +// Store the URLSession to retain its reference +private let defaultURLSession = URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: nil) + +// Store current taskDidReceiveChallenge for every URLSessionTask +private var challengeHandlerStore = SynchronizedDictionary() + +// Store current URLCredential for every URLSessionTask +private var credentialStore = SynchronizedDictionary() + +open class URLSessionRequestBuilder: RequestBuilder { + + /** + May be assigned if you want to control the authentication challenges. + */ + public var taskDidReceiveChallenge: PetstoreClientAPIChallengeHandler? + + /** + May be assigned if you want to do any of those things: + - control the task completion + - intercept and handle errors like authorization + - retry the request. + */ + @available(*, deprecated, message: "Please override execute() method to intercept and handle errors like authorization or retry the request. Check the Wiki for more info. https://github.com/OpenAPITools/openapi-generator/wiki/FAQ#how-do-i-implement-bearer-token-authentication-with-urlsession-on-the-swift-api-client") + public var taskCompletionShouldRetry: ((Data?, URLResponse?, Error?, @escaping (Bool) -> Void) -> Void)? + + required public init(method: String, URLString: String, parameters: [String: Any]?, headers: [String: String] = [:]) { + super.init(method: method, URLString: URLString, parameters: parameters, headers: headers) + } + + /** + May be overridden by a subclass if you want to control the URLSession + configuration. + */ + open func createURLSession() -> URLSession { + return defaultURLSession + } + + /** + May be overridden by a subclass if you want to control the Content-Type + that is given to an uploaded form part. + + Return nil to use the default behavior (inferring the Content-Type from + the file extension). Return the desired Content-Type otherwise. + */ + open func contentTypeForFormPart(fileURL: URL) -> String? { + return nil + } + + /** + May be overridden by a subclass if you want to control the URLRequest + configuration (e.g. to override the cache policy). + */ + open func createURLRequest(urlSession: URLSession, method: HTTPMethod, encoding: ParameterEncoding, headers: [String: String]) throws -> URLRequest { + + guard let url = URL(string: URLString) else { + throw DownloadException.requestMissingURL + } + + var originalRequest = URLRequest(url: url) + + originalRequest.httpMethod = method.rawValue + + headers.forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + buildHeaders().forEach { key, value in + originalRequest.setValue(value, forHTTPHeaderField: key) + } + + let modifiedRequest = try encoding.encode(originalRequest, with: parameters) + + return modifiedRequest + } + + @discardableResult + override open func execute(_ apiResponseQueue: DispatchQueue = PetstoreClientAPI.apiResponseQueue, _ completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) -> URLSessionTask? { + let urlSession = createURLSession() + + guard let xMethod = HTTPMethod(rawValue: method) else { + fatalError("Unsupported Http method - \(method)") + } + + let encoding: ParameterEncoding + + switch xMethod { + case .get, .head: + encoding = URLEncoding() + + case .options, .post, .put, .patch, .delete, .trace, .connect: + let contentType = headers["Content-Type"] ?? "application/json" + + if contentType == "application/json" { + encoding = JSONDataEncoding() + } else if contentType == "multipart/form-data" { + encoding = FormDataEncoding(contentTypeForFormPart: contentTypeForFormPart(fileURL:)) + } else if contentType == "application/x-www-form-urlencoded" { + encoding = FormURLEncoding() + } else { + fatalError("Unsupported Media Type - \(contentType)") + } + } + + do { + let request = try createURLRequest(urlSession: urlSession, method: xMethod, encoding: encoding, headers: headers) + + var taskIdentifier: Int? + let cleanupRequest = { + if let taskIdentifier = taskIdentifier { + challengeHandlerStore[taskIdentifier] = nil + credentialStore[taskIdentifier] = nil + } + } + + let dataTask = urlSession.dataTask(with: request) { data, response, error in + + if let taskCompletionShouldRetry = self.taskCompletionShouldRetry { + + taskCompletionShouldRetry(data, response, error) { shouldRetry in + + if shouldRetry { + cleanupRequest() + self.execute(apiResponseQueue, completion) + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + } else { + apiResponseQueue.async { + self.processRequestResponse(urlRequest: request, data: data, response: response, error: error, completion: completion) + cleanupRequest() + } + } + } + + if #available(iOS 11.0, macOS 10.13, macCatalyst 13.0, tvOS 11.0, watchOS 4.0, *) { + onProgressReady?(dataTask.progress) + } + + taskIdentifier = dataTask.taskIdentifier + challengeHandlerStore[dataTask.taskIdentifier] = taskDidReceiveChallenge + credentialStore[dataTask.taskIdentifier] = credential + + dataTask.resume() + + return dataTask + } catch { + apiResponseQueue.async { + completion(.failure(ErrorResponse.error(415, nil, nil, error))) + } + + return nil + } + } + + fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: () as! T))) + + default: + fatalError("Unsupported Response Body Type - \(String(describing: T.self))") + } + + } + + open func buildHeaders() -> [String: String] { + var httpHeaders: [String: String] = [:] + for (key, value) in headers { + httpHeaders[key] = value + } + for (key, value) in PetstoreClientAPI.customHeaders { + httpHeaders[key] = value + } + return httpHeaders + } + + fileprivate func getFileName(fromContentDisposition contentDisposition: String?) -> String? { + + guard let contentDisposition = contentDisposition else { + return nil + } + + let items = contentDisposition.components(separatedBy: ";") + + var filename: String? + + for contentItem in items { + + let filenameKey = "filename=" + guard let range = contentItem.range(of: filenameKey) else { + continue + } + + filename = contentItem + return filename? + .replacingCharacters(in: range, with: "") + .replacingOccurrences(of: "\"", with: "") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + + return filename + + } + + fileprivate func getPath(from url: URL) throws -> String { + + guard var path = URLComponents(url: url, resolvingAgainstBaseURL: true)?.path else { + throw DownloadException.requestMissingPath + } + + if path.hasPrefix("/") { + path.remove(at: path.startIndex) + } + + return path + + } + + fileprivate func getURL(from urlRequest: URLRequest) throws -> URL { + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + return url + } + +} + +open class URLSessionDecodableRequestBuilder: URLSessionRequestBuilder { + override fileprivate func processRequestResponse(urlRequest: URLRequest, data: Data?, response: URLResponse?, error: Error?, completion: @escaping (_ result: Swift.Result, ErrorResponse>) -> Void) { + + if let error = error { + completion(.failure(ErrorResponse.error(-1, data, response, error))) + return + } + + guard let httpResponse = response as? HTTPURLResponse else { + completion(.failure(ErrorResponse.error(-2, data, response, DecodableRequestBuilderError.nilHTTPResponse))) + return + } + + guard httpResponse.isStatusCodeSuccessful else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, DecodableRequestBuilderError.unsuccessfulHTTPStatusCode))) + return + } + + switch T.self { + case is String.Type: + + let body = data.flatMap { String(data: $0, encoding: .utf8) } ?? "" + + completion(.success(Response(response: httpResponse, body: body as! T))) + + case is URL.Type: + do { + + guard error == nil else { + throw DownloadException.responseFailed + } + + guard let data = data else { + throw DownloadException.responseDataMissing + } + + let fileManager = FileManager.default + let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0] + let requestURL = try getURL(from: urlRequest) + + var requestPath = try getPath(from: requestURL) + + if let headerFileName = getFileName(fromContentDisposition: httpResponse.allHeaderFields["Content-Disposition"] as? String) { + requestPath = requestPath.appending("/\(headerFileName)") + } else { + requestPath = requestPath.appending("/tmp.PetstoreClient.\(UUID().uuidString)") + } + + let filePath = cachesDirectory.appendingPathComponent(requestPath) + let directoryPath = filePath.deletingLastPathComponent().path + + try fileManager.createDirectory(atPath: directoryPath, withIntermediateDirectories: true, attributes: nil) + try data.write(to: filePath, options: .atomic) + + completion(.success(Response(response: httpResponse, body: filePath as! T))) + + } catch let requestParserError as DownloadException { + completion(.failure(ErrorResponse.error(400, data, response, requestParserError))) + } catch { + completion(.failure(ErrorResponse.error(400, data, response, error))) + } + + case is Void.Type: + + completion(.success(Response(response: httpResponse, body: () as! T))) + + case is Data.Type: + + completion(.success(Response(response: httpResponse, body: data as! T))) + + default: + + guard let data = data, !data.isEmpty else { + completion(.failure(ErrorResponse.error(httpResponse.statusCode, nil, response, DecodableRequestBuilderError.emptyDataResponse))) + return + } + + let decodeResult = CodableHelper.decode(T.self, from: data) + + switch decodeResult { + case let .success(decodableObj): + completion(.success(Response(response: httpResponse, body: decodableObj))) + case let .failure(error): + completion(.failure(ErrorResponse.error(httpResponse.statusCode, data, response, error))) + } + } + } +} + +private class SessionDelegate: NSObject, URLSessionTaskDelegate { + func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) { + + var disposition: URLSession.AuthChallengeDisposition = .performDefaultHandling + + var credential: URLCredential? + + if let taskDidReceiveChallenge = challengeHandlerStore[task.taskIdentifier] { + (disposition, credential) = taskDidReceiveChallenge(session, task, challenge) + } else { + if challenge.previousFailureCount > 0 { + disposition = .rejectProtectionSpace + } else { + credential = credentialStore[task.taskIdentifier] ?? session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace) + + if credential != nil { + disposition = .useCredential + } + } + } + + completionHandler(disposition, credential) + } +} + +public enum HTTPMethod: String { + case options = "OPTIONS" + case get = "GET" + case head = "HEAD" + case post = "POST" + case put = "PUT" + case patch = "PATCH" + case delete = "DELETE" + case trace = "TRACE" + case connect = "CONNECT" +} + +public protocol ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest +} + +private class URLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters else { return urlRequest } + + guard let url = urlRequest.url else { + throw DownloadException.requestMissingURL + } + + if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { + urlComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters) + urlRequest.url = urlComponents.url + } + + return urlRequest + } +} + +private class FormDataEncoding: ParameterEncoding { + + let contentTypeForFormPart: (_ fileURL: URL) -> String? + + init(contentTypeForFormPart: @escaping (_ fileURL: URL) -> String?) { + self.contentTypeForFormPart = contentTypeForFormPart + } + + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + guard let parameters = parameters, !parameters.isEmpty else { + return urlRequest + } + + let boundary = "Boundary-\(UUID().uuidString)" + + urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") + + for (key, value) in parameters { + switch value { + case let fileURL as URL: + + urlRequest = try configureFileUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + fileURL: fileURL + ) + + case let string as String: + + if let data = string.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + case let number as NSNumber: + + if let data = number.stringValue.data(using: .utf8) { + urlRequest = configureDataUploadRequest( + urlRequest: urlRequest, + boundary: boundary, + name: key, + data: data + ) + } + + default: + fatalError("Unprocessable value \(value) with key \(key)") + } + } + + var body = urlRequest.httpBody.orEmpty + + body.append("\r\n--\(boundary)--\r\n") + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureFileUploadRequest(urlRequest: URLRequest, boundary: String, name: String, fileURL: URL) throws -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + let fileData = try Data(contentsOf: fileURL) + + let mimetype = contentTypeForFormPart(fileURL) ?? mimeType(for: fileURL) + + let fileName = fileURL.lastPathComponent + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"; filename=\"\(fileName)\"\r\n") + body.append("Content-Type: \(mimetype)\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(fileData) + + urlRequest.httpBody = body + + return urlRequest + } + + private func configureDataUploadRequest(urlRequest: URLRequest, boundary: String, name: String, data: Data) -> URLRequest { + + var urlRequest = urlRequest + + var body = urlRequest.httpBody.orEmpty + + // If we already added something then we need an additional newline. + if body.count > 0 { + body.append("\r\n") + } + + // Value boundary. + body.append("--\(boundary)\r\n") + + // Value headers. + body.append("Content-Disposition: form-data; name=\"\(name)\"\r\n") + + // Separate headers and body. + body.append("\r\n") + + // The value data. + body.append(data) + + urlRequest.httpBody = body + + return urlRequest + + } + + func mimeType(for url: URL) -> String { + let pathExtension = url.pathExtension + + if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as NSString, nil)?.takeRetainedValue() { + if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { + return mimetype as String + } + } + return "application/octet-stream" + } + +} + +private class FormURLEncoding: ParameterEncoding { + func encode(_ urlRequest: URLRequest, with parameters: [String: Any]?) throws -> URLRequest { + + var urlRequest = urlRequest + + var requestBodyComponents = URLComponents() + requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + + if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { + urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") + } + + urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + + return urlRequest + } +} + +private extension Data { + /// Append string to Data + /// + /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to Data, and then add that data to the Data, this wraps it in a nice convenient little extension to Data. This converts using UTF-8. + /// + /// - parameter string: The string to be added to the `Data`. + + mutating func append(_ string: String) { + if let data = string.data(using: .utf8) { + append(data) + } + } +} + +private extension Optional where Wrapped == Data { + var orEmpty: Data { + self ?? Data() + } +} + +extension JSONDataEncoding: ParameterEncoding {} diff --git a/samples/client/petstore/swift5/frozenEnums/README.md b/samples/client/petstore/swift5/frozenEnums/README.md new file mode 100644 index 00000000000..1725415f7e0 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/README.md @@ -0,0 +1,141 @@ +# Swift5 API client for PetstoreClient + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.Swift5ClientCodegen + +## Installation + +### Carthage + +Run `carthage update` + +### CocoaPods + +Run `pod install` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AnotherFakeAPI* | [**call123testSpecialTags**](docs/AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags +*FakeAPI* | [**fakeOuterBooleanSerialize**](docs/FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +*FakeAPI* | [**fakeOuterCompositeSerialize**](docs/FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +*FakeAPI* | [**fakeOuterNumberSerialize**](docs/FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +*FakeAPI* | [**fakeOuterStringSerialize**](docs/FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +*FakeAPI* | [**testBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +*FakeAPI* | [**testBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +*FakeAPI* | [**testClientModel**](docs/FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +*FakeAPI* | [**testEndpointParameters**](docs/FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeAPI* | [**testEnumParameters**](docs/FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +*FakeAPI* | [**testGroupParameters**](docs/FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +*FakeAPI* | [**testInlineAdditionalProperties**](docs/FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +*FakeAPI* | [**testJsonFormData**](docs/FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data +*FakeClassnameTags123API* | [**testClassname**](docs/FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case +*PetAPI* | [**addPet**](docs/PetAPI.md#addpet) | **POST** /pet | Add a new pet to the store +*PetAPI* | [**deletePet**](docs/PetAPI.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetAPI* | [**findPetsByStatus**](docs/PetAPI.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetAPI* | [**findPetsByTags**](docs/PetAPI.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetAPI* | [**getPetById**](docs/PetAPI.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetAPI* | [**updatePet**](docs/PetAPI.md#updatepet) | **PUT** /pet | Update an existing pet +*PetAPI* | [**updatePetWithForm**](docs/PetAPI.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetAPI* | [**uploadFile**](docs/PetAPI.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*PetAPI* | [**uploadFileWithRequiredFile**](docs/PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) +*StoreAPI* | [**deleteOrder**](docs/StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +*StoreAPI* | [**getInventory**](docs/StoreAPI.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreAPI* | [**getOrderById**](docs/StoreAPI.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +*StoreAPI* | [**placeOrder**](docs/StoreAPI.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserAPI* | [**createUser**](docs/UserAPI.md#createuser) | **POST** /user | Create user +*UserAPI* | [**createUsersWithArrayInput**](docs/UserAPI.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserAPI* | [**createUsersWithListInput**](docs/UserAPI.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserAPI* | [**deleteUser**](docs/UserAPI.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserAPI* | [**getUserByName**](docs/UserAPI.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserAPI* | [**loginUser**](docs/UserAPI.md#loginuser) | **GET** /user/login | Logs user into the system +*UserAPI* | [**logoutUser**](docs/UserAPI.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserAPI* | [**updateUser**](docs/UserAPI.md#updateuser) | **PUT** /user/{username} | Updated user + + +## Documentation For Models + + - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [Animal](docs/Animal.md) + - [AnimalFarm](docs/AnimalFarm.md) + - [ApiResponse](docs/ApiResponse.md) + - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) + - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) + - [ArrayTest](docs/ArrayTest.md) + - [Capitalization](docs/Capitalization.md) + - [Cat](docs/Cat.md) + - [CatAllOf](docs/CatAllOf.md) + - [Category](docs/Category.md) + - [ClassModel](docs/ClassModel.md) + - [Client](docs/Client.md) + - [Dog](docs/Dog.md) + - [DogAllOf](docs/DogAllOf.md) + - [EnumArrays](docs/EnumArrays.md) + - [EnumClass](docs/EnumClass.md) + - [EnumTest](docs/EnumTest.md) + - [File](docs/File.md) + - [FileSchemaTestClass](docs/FileSchemaTestClass.md) + - [FormatTest](docs/FormatTest.md) + - [HasOnlyReadOnly](docs/HasOnlyReadOnly.md) + - [List](docs/List.md) + - [MapTest](docs/MapTest.md) + - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) + - [Model200Response](docs/Model200Response.md) + - [Name](docs/Name.md) + - [NumberOnly](docs/NumberOnly.md) + - [Order](docs/Order.md) + - [OuterComposite](docs/OuterComposite.md) + - [OuterEnum](docs/OuterEnum.md) + - [Pet](docs/Pet.md) + - [ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Return](docs/Return.md) + - [SpecialModelName](docs/SpecialModelName.md) + - [StringBooleanMap](docs/StringBooleanMap.md) + - [Tag](docs/Tag.md) + - [TypeHolderDefault](docs/TypeHolderDefault.md) + - [TypeHolderExample](docs/TypeHolderExample.md) + - [User](docs/User.md) + + +## Documentation For Authorization + + +## api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + +## api_key_query + +- **Type**: API key +- **API key parameter name**: api_key_query +- **Location**: URL query string + +## http_basic_test + +- **Type**: HTTP basic authentication + +## petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + + +## Author + + + diff --git a/samples/client/petstore/swift5/frozenEnums/docs/AdditionalPropertiesClass.md b/samples/client/petstore/swift5/frozenEnums/docs/AdditionalPropertiesClass.md new file mode 100644 index 00000000000..1f222244134 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/AdditionalPropertiesClass.md @@ -0,0 +1,11 @@ +# AdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapString** | **[String: String]** | | [optional] +**mapMapString** | [String: [String: String]] | | [optional] + +[[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/swift5/frozenEnums/docs/Animal.md b/samples/client/petstore/swift5/frozenEnums/docs/Animal.md new file mode 100644 index 00000000000..69c601455cd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Animal.md @@ -0,0 +1,11 @@ +# Animal + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**className** | **String** | | +**color** | **String** | | [optional] [default to "red"] + +[[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/swift5/frozenEnums/docs/AnimalFarm.md b/samples/client/petstore/swift5/frozenEnums/docs/AnimalFarm.md new file mode 100644 index 00000000000..df6bab21dae --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/AnimalFarm.md @@ -0,0 +1,9 @@ +# AnimalFarm + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/frozenEnums/docs/AnotherFakeAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/AnotherFakeAPI.md new file mode 100644 index 00000000000..26346e81a4c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/AnotherFakeAPI.md @@ -0,0 +1,59 @@ +# AnotherFakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**call123testSpecialTags**](AnotherFakeAPI.md#call123testspecialtags) | **PATCH** /another-fake/dummy | To test special tags + + +# **call123testSpecialTags** +```swift + open class func call123testSpecialTags(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test special tags + +To test special tags and operation ID starting with number + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test special tags +AnotherFakeAPI.call123testSpecialTags(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **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/client/petstore/swift5/frozenEnums/docs/ApiResponse.md b/samples/client/petstore/swift5/frozenEnums/docs/ApiResponse.md new file mode 100644 index 00000000000..c6d9768fe9b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ApiResponse.md @@ -0,0 +1,12 @@ +# ApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Int** | | [optional] +**type** | **String** | | [optional] +**message** | **String** | | [optional] + +[[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/swift5/frozenEnums/docs/ArrayOfArrayOfNumberOnly.md b/samples/client/petstore/swift5/frozenEnums/docs/ArrayOfArrayOfNumberOnly.md new file mode 100644 index 00000000000..c6fceff5e08 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ArrayOfArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayArrayNumber** | [[Double]] | | [optional] + +[[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/swift5/frozenEnums/docs/ArrayOfNumberOnly.md b/samples/client/petstore/swift5/frozenEnums/docs/ArrayOfNumberOnly.md new file mode 100644 index 00000000000..f09f8fa6f70 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ArrayOfNumberOnly.md @@ -0,0 +1,10 @@ +# ArrayOfNumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayNumber** | **[Double]** | | [optional] + +[[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/swift5/frozenEnums/docs/ArrayTest.md b/samples/client/petstore/swift5/frozenEnums/docs/ArrayTest.md new file mode 100644 index 00000000000..bf416b8330c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ArrayTest.md @@ -0,0 +1,12 @@ +# ArrayTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**arrayOfString** | **[String]** | | [optional] +**arrayArrayOfInteger** | [[Int64]] | | [optional] +**arrayArrayOfModel** | [[ReadOnlyFirst]] | | [optional] + +[[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/swift5/frozenEnums/docs/Capitalization.md b/samples/client/petstore/swift5/frozenEnums/docs/Capitalization.md new file mode 100644 index 00000000000..95374216c77 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Capitalization.md @@ -0,0 +1,15 @@ +# Capitalization + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**smallCamel** | **String** | | [optional] +**capitalCamel** | **String** | | [optional] +**smallSnake** | **String** | | [optional] +**capitalSnake** | **String** | | [optional] +**sCAETHFlowPoints** | **String** | | [optional] +**ATT_NAME** | **String** | Name of the pet | [optional] + +[[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/swift5/frozenEnums/docs/Cat.md b/samples/client/petstore/swift5/frozenEnums/docs/Cat.md new file mode 100644 index 00000000000..fb5949b1576 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Cat.md @@ -0,0 +1,10 @@ +# Cat + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Bool** | | [optional] + +[[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/swift5/frozenEnums/docs/CatAllOf.md b/samples/client/petstore/swift5/frozenEnums/docs/CatAllOf.md new file mode 100644 index 00000000000..79789be61c0 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/CatAllOf.md @@ -0,0 +1,10 @@ +# CatAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**declawed** | **Bool** | | [optional] + +[[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/swift5/frozenEnums/docs/Category.md b/samples/client/petstore/swift5/frozenEnums/docs/Category.md new file mode 100644 index 00000000000..5ca5408c0f9 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Category.md @@ -0,0 +1,11 @@ +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**name** | **String** | | [default to "default-name"] + +[[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/swift5/frozenEnums/docs/ClassModel.md b/samples/client/petstore/swift5/frozenEnums/docs/ClassModel.md new file mode 100644 index 00000000000..e3912fdf0fd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ClassModel.md @@ -0,0 +1,10 @@ +# ClassModel + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_class** | **String** | | [optional] + +[[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/swift5/frozenEnums/docs/Client.md b/samples/client/petstore/swift5/frozenEnums/docs/Client.md new file mode 100644 index 00000000000..0de1b238c36 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Client.md @@ -0,0 +1,10 @@ +# Client + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**client** | **String** | | [optional] + +[[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/swift5/frozenEnums/docs/Dog.md b/samples/client/petstore/swift5/frozenEnums/docs/Dog.md new file mode 100644 index 00000000000..4824786da04 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Dog.md @@ -0,0 +1,10 @@ +# Dog + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + +[[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/swift5/frozenEnums/docs/DogAllOf.md b/samples/client/petstore/swift5/frozenEnums/docs/DogAllOf.md new file mode 100644 index 00000000000..9302ef52e93 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/DogAllOf.md @@ -0,0 +1,10 @@ +# DogAllOf + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**breed** | **String** | | [optional] + +[[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/swift5/frozenEnums/docs/EnumArrays.md b/samples/client/petstore/swift5/frozenEnums/docs/EnumArrays.md new file mode 100644 index 00000000000..b9a9807d3c8 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/EnumArrays.md @@ -0,0 +1,11 @@ +# EnumArrays + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justSymbol** | **String** | | [optional] +**arrayEnum** | **[String]** | | [optional] + +[[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/swift5/frozenEnums/docs/EnumClass.md b/samples/client/petstore/swift5/frozenEnums/docs/EnumClass.md new file mode 100644 index 00000000000..67f017becd0 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/EnumClass.md @@ -0,0 +1,9 @@ +# EnumClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/frozenEnums/docs/EnumTest.md b/samples/client/petstore/swift5/frozenEnums/docs/EnumTest.md new file mode 100644 index 00000000000..bc9b036dd76 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/EnumTest.md @@ -0,0 +1,14 @@ +# EnumTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**enumString** | **String** | | [optional] +**enumStringRequired** | **String** | | +**enumInteger** | **Int** | | [optional] +**enumNumber** | **Double** | | [optional] +**outerEnum** | [**OuterEnum**](OuterEnum.md) | | [optional] + +[[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/swift5/frozenEnums/docs/FakeAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/FakeAPI.md new file mode 100644 index 00000000000..e33bd2d35fb --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/FakeAPI.md @@ -0,0 +1,662 @@ +# FakeAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**fakeOuterBooleanSerialize**](FakeAPI.md#fakeouterbooleanserialize) | **POST** /fake/outer/boolean | +[**fakeOuterCompositeSerialize**](FakeAPI.md#fakeoutercompositeserialize) | **POST** /fake/outer/composite | +[**fakeOuterNumberSerialize**](FakeAPI.md#fakeouternumberserialize) | **POST** /fake/outer/number | +[**fakeOuterStringSerialize**](FakeAPI.md#fakeouterstringserialize) | **POST** /fake/outer/string | +[**testBodyWithFileSchema**](FakeAPI.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | +[**testBodyWithQueryParams**](FakeAPI.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | +[**testClientModel**](FakeAPI.md#testclientmodel) | **PATCH** /fake | To test \"client\" model +[**testEndpointParameters**](FakeAPI.md#testendpointparameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**testEnumParameters**](FakeAPI.md#testenumparameters) | **GET** /fake | To test enum parameters +[**testGroupParameters**](FakeAPI.md#testgroupparameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) +[**testInlineAdditionalProperties**](FakeAPI.md#testinlineadditionalproperties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties +[**testJsonFormData**](FakeAPI.md#testjsonformdata) | **GET** /fake/jsonFormData | test json serialization of form data + + +# **fakeOuterBooleanSerialize** +```swift + open class func fakeOuterBooleanSerialize(body: Bool? = nil, completion: @escaping (_ data: Bool?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer boolean types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = true // Bool | Input boolean as post body (optional) + +FakeAPI.fakeOuterBooleanSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Bool** | Input boolean as post body | [optional] + +### Return type + +**Bool** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterCompositeSerialize** +```swift + open class func fakeOuterCompositeSerialize(body: OuterComposite? = nil, completion: @escaping (_ data: OuterComposite?, _ error: Error?) -> Void) +``` + + + +Test serialization of object with outer number type + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = OuterComposite(myNumber: 123, myString: "myString_example", myBoolean: false) // OuterComposite | Input composite as post body (optional) + +FakeAPI.fakeOuterCompositeSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**OuterComposite**](OuterComposite.md) | Input composite as post body | [optional] + +### Return type + +[**OuterComposite**](OuterComposite.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterNumberSerialize** +```swift + open class func fakeOuterNumberSerialize(body: Double? = nil, completion: @escaping (_ data: Double?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer number types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = 987 // Double | Input number as post body (optional) + +FakeAPI.fakeOuterNumberSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **Double** | Input number as post body | [optional] + +### Return type + +**Double** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **fakeOuterStringSerialize** +```swift + open class func fakeOuterStringSerialize(body: String? = nil, completion: @escaping (_ data: String?, _ error: Error?) -> Void) +``` + + + +Test serialization of outer string types + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = "body_example" // String | Input string as post body (optional) + +FakeAPI.fakeOuterStringSerialize(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | **String** | Input string as post body | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: */* + +[[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) + +# **testBodyWithFileSchema** +```swift + open class func testBodyWithFileSchema(body: FileSchemaTestClass, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + + + +For this test, the body for this request much reference a schema named `File`. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = FileSchemaTestClass(file: File(sourceURI: "sourceURI_example"), files: [nil]) // FileSchemaTestClass | + +FakeAPI.testBodyWithFileSchema(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**FileSchemaTestClass**](FileSchemaTestClass.md) | | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[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) + +# **testBodyWithQueryParams** +```swift + open class func testBodyWithQueryParams(query: String, body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + + + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let query = "query_example" // String | +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | + +FakeAPI.testBodyWithQueryParams(query: query, body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **query** | **String** | | + **body** | [**User**](User.md) | | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[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) + +# **testClientModel** +```swift + open class func testClientModel(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test \"client\" model + +To test \"client\" model + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test \"client\" model +FakeAPI.testClientModel(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **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) + +# **testEndpointParameters** +```swift + open class func testEndpointParameters(integer: Int? = nil, int32: Int? = nil, int64: Int64? = nil, number: Double, float: Float? = nil, double: Double, string: String? = nil, patternWithoutDelimiter: String, byte: Data, binary: URL? = nil, date: Date? = nil, dateTime: Date? = nil, password: String? = nil, callback: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let integer = 987 // Int | None (optional) +let int32 = 987 // Int | None (optional) +let int64 = 987 // Int64 | None (optional) +let number = 987 // Double | None +let float = 987 // Float | None (optional) +let double = 987 // Double | None +let string = "string_example" // String | None (optional) +let patternWithoutDelimiter = "patternWithoutDelimiter_example" // String | None +let byte = Data([9, 8, 7]) // Data | None +let binary = URL(string: "https://example.com")! // URL | None (optional) +let date = Date() // Date | None (optional) +let dateTime = Date() // Date | None (optional) +let password = "password_example" // String | None (optional) +let callback = "callback_example" // String | None (optional) + +// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +FakeAPI.testEndpointParameters(integer: integer, int32: int32, int64: int64, number: number, float: float, double: double, string: string, patternWithoutDelimiter: patternWithoutDelimiter, byte: byte, binary: binary, date: date, dateTime: dateTime, password: password, callback: callback) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **integer** | **Int** | None | [optional] + **int32** | **Int** | None | [optional] + **int64** | **Int64** | None | [optional] + **number** | **Double** | None | + **float** | **Float** | None | [optional] + **double** | **Double** | None | + **string** | **String** | None | [optional] + **patternWithoutDelimiter** | **String** | None | + **byte** | **Data** | None | + **binary** | **URL** | None | [optional] + **date** | **Date** | None | [optional] + **dateTime** | **Date** | None | [optional] + **password** | **String** | None | [optional] + **callback** | **String** | None | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +[http_basic_test](../README.md#http_basic_test) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[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) + +# **testEnumParameters** +```swift + open class func testEnumParameters(enumHeaderStringArray: [EnumHeaderStringArray_testEnumParameters]? = nil, enumHeaderString: EnumHeaderString_testEnumParameters? = nil, enumQueryStringArray: [EnumQueryStringArray_testEnumParameters]? = nil, enumQueryString: EnumQueryString_testEnumParameters? = nil, enumQueryInteger: EnumQueryInteger_testEnumParameters? = nil, enumQueryDouble: EnumQueryDouble_testEnumParameters? = nil, enumFormStringArray: [EnumFormStringArray_testEnumParameters]? = nil, enumFormString: EnumFormString_testEnumParameters? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +To test enum parameters + +To test enum parameters + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let enumHeaderStringArray = ["enumHeaderStringArray_example"] // [String] | Header parameter enum test (string array) (optional) +let enumHeaderString = "enumHeaderString_example" // String | Header parameter enum test (string) (optional) (default to .efg) +let enumQueryStringArray = ["enumQueryStringArray_example"] // [String] | Query parameter enum test (string array) (optional) +let enumQueryString = "enumQueryString_example" // String | Query parameter enum test (string) (optional) (default to .efg) +let enumQueryInteger = 987 // Int | Query parameter enum test (double) (optional) +let enumQueryDouble = 987 // Double | Query parameter enum test (double) (optional) +let enumFormStringArray = ["inner_example"] // [String] | Form parameter enum test (string array) (optional) (default to .dollar) +let enumFormString = "enumFormString_example" // String | Form parameter enum test (string) (optional) (default to .efg) + +// To test enum parameters +FakeAPI.testEnumParameters(enumHeaderStringArray: enumHeaderStringArray, enumHeaderString: enumHeaderString, enumQueryStringArray: enumQueryStringArray, enumQueryString: enumQueryString, enumQueryInteger: enumQueryInteger, enumQueryDouble: enumQueryDouble, enumFormStringArray: enumFormStringArray, enumFormString: enumFormString) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **enumHeaderStringArray** | [**[String]**](String.md) | Header parameter enum test (string array) | [optional] + **enumHeaderString** | **String** | Header parameter enum test (string) | [optional] [default to .efg] + **enumQueryStringArray** | [**[String]**](String.md) | Query parameter enum test (string array) | [optional] + **enumQueryString** | **String** | Query parameter enum test (string) | [optional] [default to .efg] + **enumQueryInteger** | **Int** | Query parameter enum test (double) | [optional] + **enumQueryDouble** | **Double** | Query parameter enum test (double) | [optional] + **enumFormStringArray** | [**[String]**](String.md) | Form parameter enum test (string array) | [optional] [default to .dollar] + **enumFormString** | **String** | Form parameter enum test (string) | [optional] [default to .efg] + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[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) + +# **testGroupParameters** +```swift + open class func testGroupParameters(requiredStringGroup: Int, requiredBooleanGroup: Bool, requiredInt64Group: Int64, stringGroup: Int? = nil, booleanGroup: Bool? = nil, int64Group: Int64? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Fake endpoint to test group parameters (optional) + +Fake endpoint to test group parameters (optional) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let requiredStringGroup = 987 // Int | Required String in group parameters +let requiredBooleanGroup = true // Bool | Required Boolean in group parameters +let requiredInt64Group = 987 // Int64 | Required Integer in group parameters +let stringGroup = 987 // Int | String in group parameters (optional) +let booleanGroup = true // Bool | Boolean in group parameters (optional) +let int64Group = 987 // Int64 | Integer in group parameters (optional) + +// Fake endpoint to test group parameters (optional) +FakeAPI.testGroupParameters(requiredStringGroup: requiredStringGroup, requiredBooleanGroup: requiredBooleanGroup, requiredInt64Group: requiredInt64Group, stringGroup: stringGroup, booleanGroup: booleanGroup, int64Group: int64Group) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requiredStringGroup** | **Int** | Required String in group parameters | + **requiredBooleanGroup** | **Bool** | Required Boolean in group parameters | + **requiredInt64Group** | **Int64** | Required Integer in group parameters | + **stringGroup** | **Int** | String in group parameters | [optional] + **booleanGroup** | **Bool** | Boolean in group parameters | [optional] + **int64Group** | **Int64** | Integer in group parameters | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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) + +# **testInlineAdditionalProperties** +```swift + open class func testInlineAdditionalProperties(param: [String: String], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +test inline additionalProperties + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "TODO" // [String: String] | request body + +// test inline additionalProperties +FakeAPI.testInlineAdditionalProperties(param: param) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | [**[String: String]**](String.md) | request body | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[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) + +# **testJsonFormData** +```swift + open class func testJsonFormData(param: String, param2: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +test json serialization of form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let param = "param_example" // String | field1 +let param2 = "param2_example" // String | field2 + +// test json serialization of form data +FakeAPI.testJsonFormData(param: param, param2: param2) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **param** | **String** | field1 | + **param2** | **String** | field2 | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[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/client/petstore/swift5/frozenEnums/docs/FakeClassnameTags123API.md b/samples/client/petstore/swift5/frozenEnums/docs/FakeClassnameTags123API.md new file mode 100644 index 00000000000..5b9b66073fe --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/FakeClassnameTags123API.md @@ -0,0 +1,59 @@ +# FakeClassnameTags123API + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**testClassname**](FakeClassnameTags123API.md#testclassname) | **PATCH** /fake_classname_test | To test class name in snake case + + +# **testClassname** +```swift + open class func testClassname(body: Client, completion: @escaping (_ data: Client?, _ error: Error?) -> Void) +``` + +To test class name in snake case + +To test class name in snake case + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Client(client: "client_example") // Client | client model + +// To test class name in snake case +FakeClassnameTags123API.testClassname(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Client**](Client.md) | client model | + +### Return type + +[**Client**](Client.md) + +### Authorization + +[api_key_query](../README.md#api_key_query) + +### HTTP request headers + + - **Content-Type**: application/json + - **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/client/petstore/swift5/frozenEnums/docs/File.md b/samples/client/petstore/swift5/frozenEnums/docs/File.md new file mode 100644 index 00000000000..3edfef17b79 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/File.md @@ -0,0 +1,10 @@ +# File + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**sourceURI** | **String** | Test capitalization | [optional] + +[[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/swift5/frozenEnums/docs/FileSchemaTestClass.md b/samples/client/petstore/swift5/frozenEnums/docs/FileSchemaTestClass.md new file mode 100644 index 00000000000..afdacc60b2c --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/FileSchemaTestClass.md @@ -0,0 +1,11 @@ +# FileSchemaTestClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**file** | [**File**](File.md) | | [optional] +**files** | [File] | | [optional] + +[[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/swift5/frozenEnums/docs/FormatTest.md b/samples/client/petstore/swift5/frozenEnums/docs/FormatTest.md new file mode 100644 index 00000000000..f74d94f6c46 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/FormatTest.md @@ -0,0 +1,22 @@ +# FormatTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**integer** | **Int** | | [optional] +**int32** | **Int** | | [optional] +**int64** | **Int64** | | [optional] +**number** | **Double** | | +**float** | **Float** | | [optional] +**double** | **Double** | | [optional] +**string** | **String** | | [optional] +**byte** | **Data** | | +**binary** | **URL** | | [optional] +**date** | **Date** | | +**dateTime** | **Date** | | [optional] +**uuid** | **UUID** | | [optional] +**password** | **String** | | + +[[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/swift5/frozenEnums/docs/HasOnlyReadOnly.md b/samples/client/petstore/swift5/frozenEnums/docs/HasOnlyReadOnly.md new file mode 100644 index 00000000000..57b6e3a17e6 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/HasOnlyReadOnly.md @@ -0,0 +1,11 @@ +# HasOnlyReadOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**foo** | **String** | | [optional] [readonly] + +[[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/swift5/frozenEnums/docs/List.md b/samples/client/petstore/swift5/frozenEnums/docs/List.md new file mode 100644 index 00000000000..b77718302ed --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/List.md @@ -0,0 +1,10 @@ +# List + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_123list** | **String** | | [optional] + +[[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/swift5/frozenEnums/docs/MapTest.md b/samples/client/petstore/swift5/frozenEnums/docs/MapTest.md new file mode 100644 index 00000000000..73f9e0d50ac --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/MapTest.md @@ -0,0 +1,13 @@ +# MapTest + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**mapMapOfString** | [String: [String: String]] | | [optional] +**mapOfEnumString** | **[String: String]** | | [optional] +**directMap** | **[String: Bool]** | | [optional] +**indirectMap** | [**StringBooleanMap**](StringBooleanMap.md) | | [optional] + +[[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/swift5/frozenEnums/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/client/petstore/swift5/frozenEnums/docs/MixedPropertiesAndAdditionalPropertiesClass.md new file mode 100644 index 00000000000..3fdfd03f0e3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -0,0 +1,12 @@ +# MixedPropertiesAndAdditionalPropertiesClass + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**uuid** | **UUID** | | [optional] +**dateTime** | **Date** | | [optional] +**map** | [String: Animal] | | [optional] + +[[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/swift5/frozenEnums/docs/Model200Response.md b/samples/client/petstore/swift5/frozenEnums/docs/Model200Response.md new file mode 100644 index 00000000000..5865ea690cc --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Model200Response.md @@ -0,0 +1,11 @@ +# Model200Response + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | [optional] +**_class** | **String** | | [optional] + +[[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/swift5/frozenEnums/docs/Name.md b/samples/client/petstore/swift5/frozenEnums/docs/Name.md new file mode 100644 index 00000000000..f7b180292cd --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Name.md @@ -0,0 +1,13 @@ +# Name + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **Int** | | +**snakeCase** | **Int** | | [optional] [readonly] +**property** | **String** | | [optional] +**_123number** | **Int** | | [optional] [readonly] + +[[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/swift5/frozenEnums/docs/NumberOnly.md b/samples/client/petstore/swift5/frozenEnums/docs/NumberOnly.md new file mode 100644 index 00000000000..72bd361168b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/NumberOnly.md @@ -0,0 +1,10 @@ +# NumberOnly + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**justNumber** | **Double** | | [optional] + +[[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/swift5/frozenEnums/docs/Order.md b/samples/client/petstore/swift5/frozenEnums/docs/Order.md new file mode 100644 index 00000000000..15487f01175 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Order.md @@ -0,0 +1,15 @@ +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**petId** | **Int64** | | [optional] +**quantity** | **Int** | | [optional] +**shipDate** | **Date** | | [optional] +**status** | **String** | Order Status | [optional] +**complete** | **Bool** | | [optional] [default to false] + +[[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/swift5/frozenEnums/docs/OuterComposite.md b/samples/client/petstore/swift5/frozenEnums/docs/OuterComposite.md new file mode 100644 index 00000000000..d6b3583bc3f --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/OuterComposite.md @@ -0,0 +1,12 @@ +# OuterComposite + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**myNumber** | **Double** | | [optional] +**myString** | **String** | | [optional] +**myBoolean** | **Bool** | | [optional] + +[[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/swift5/frozenEnums/docs/OuterEnum.md b/samples/client/petstore/swift5/frozenEnums/docs/OuterEnum.md new file mode 100644 index 00000000000..06d413b0168 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/OuterEnum.md @@ -0,0 +1,9 @@ +# OuterEnum + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/frozenEnums/docs/Pet.md b/samples/client/petstore/swift5/frozenEnums/docs/Pet.md new file mode 100644 index 00000000000..5c05f98fad4 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Pet.md @@ -0,0 +1,15 @@ +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **[String]** | | +**tags** | [Tag] | | [optional] +**status** | **String** | pet status in the store | [optional] + +[[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/swift5/frozenEnums/docs/PetAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/PetAPI.md new file mode 100644 index 00000000000..37226f18b85 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/PetAPI.md @@ -0,0 +1,469 @@ +# PetAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetAPI.md#addpet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetAPI.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetAPI.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetAPI.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetAPI.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetAPI.md#updatepet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetAPI.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetAPI.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**uploadFileWithRequiredFile**](PetAPI.md#uploadfilewithrequiredfile) | **POST** /fake/{petId}/uploadImageWithRequiredFile | uploads an image (required) + + +# **addPet** +```swift + open class func addPet(body: Pet, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Add a new pet to the store + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Add a new pet to the store +PetAPI.addPet(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +[[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) + +# **deletePet** +```swift + open class func deletePet(apiKey: String? = nil, petId: Int64, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Deletes a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let apiKey = "apiKey_example" // String | (optional) +let petId = 987 // Int64 | Pet id to delete + +// Deletes a pet +PetAPI.deletePet(apiKey: apiKey, petId: petId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **apiKey** | **String** | | [optional] + **petId** | **Int64** | Pet id to delete | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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) + +# **findPetsByStatus** +```swift + open class func findPetsByStatus(status: [Status_findPetsByStatus], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) +``` + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let status = ["status_example"] // [String] | Status values that need to be considered for filter + +// Finds Pets by status +PetAPI.findPetsByStatus(status: status) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**[String]**](String.md) | Status values that need to be considered for filter | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, 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) + +# **findPetsByTags** +```swift + open class func findPetsByTags(tags: [String], completion: @escaping (_ data: [Pet]?, _ error: Error?) -> Void) +``` + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let tags = ["inner_example"] // [String] | Tags to filter by + +// Finds Pets by tags +PetAPI.findPetsByTags(tags: tags) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**[String]**](String.md) | Tags to filter by | + +### Return type + +[**[Pet]**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, 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) + +# **getPetById** +```swift + open class func getPetById(petId: Int64, completion: @escaping (_ data: Pet?, _ error: Error?) -> Void) +``` + +Find pet by ID + +Returns a single pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to return + +// Find pet by ID +PetAPI.getPetById(petId: petId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, 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) + +# **updatePet** +```swift + open class func updatePet(body: Pet, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Update an existing pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Pet(id: 123, category: Category(id: 123, name: "name_example"), name: "name_example", photoUrls: ["photoUrls_example"], tags: [Tag(id: 123, name: "name_example")], status: "status_example") // Pet | Pet object that needs to be added to the store + +// Update an existing pet +PetAPI.updatePet(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + +[[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) + +# **updatePetWithForm** +```swift + open class func updatePetWithForm(petId: Int64, name: String? = nil, status: String? = nil, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Updates a pet in the store with form data + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet that needs to be updated +let name = "name_example" // String | Updated name of the pet (optional) +let status = "status_example" // String | Updated status of the pet (optional) + +// Updates a pet in the store with form data +PetAPI.updatePetWithForm(petId: petId, name: name, status: status) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet that needs to be updated | + **name** | **String** | Updated name of the pet | [optional] + **status** | **String** | Updated status of the pet | [optional] + +### Return type + +Void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + +[[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) + +# **uploadFile** +```swift + open class func uploadFile(petId: Int64, additionalMetadata: String? = nil, file: URL? = nil, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) +``` + +uploads an image + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) +let file = URL(string: "https://example.com")! // URL | file to upload (optional) + +// uploads an image +PetAPI.uploadFile(petId: petId, additionalMetadata: additionalMetadata, file: file) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + **file** | **URL** | file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **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) + +# **uploadFileWithRequiredFile** +```swift + open class func uploadFileWithRequiredFile(petId: Int64, additionalMetadata: String? = nil, requiredFile: URL, completion: @escaping (_ data: ApiResponse?, _ error: Error?) -> Void) +``` + +uploads an image (required) + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let petId = 987 // Int64 | ID of pet to update +let additionalMetadata = "additionalMetadata_example" // String | Additional data to pass to server (optional) +let requiredFile = URL(string: "https://example.com")! // URL | file to upload + +// uploads an image (required) +PetAPI.uploadFileWithRequiredFile(petId: petId, additionalMetadata: additionalMetadata, requiredFile: requiredFile) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Int64** | ID of pet to update | + **additionalMetadata** | **String** | Additional data to pass to server | [optional] + **requiredFile** | **URL** | file to upload | + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **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/client/petstore/swift5/frozenEnums/docs/ReadOnlyFirst.md b/samples/client/petstore/swift5/frozenEnums/docs/ReadOnlyFirst.md new file mode 100644 index 00000000000..ed537b87598 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/ReadOnlyFirst.md @@ -0,0 +1,11 @@ +# ReadOnlyFirst + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**bar** | **String** | | [optional] [readonly] +**baz** | **String** | | [optional] + +[[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/swift5/frozenEnums/docs/Return.md b/samples/client/petstore/swift5/frozenEnums/docs/Return.md new file mode 100644 index 00000000000..66d17c27c88 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Return.md @@ -0,0 +1,10 @@ +# Return + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**_return** | **Int** | | [optional] + +[[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/swift5/frozenEnums/docs/SpecialModelName.md b/samples/client/petstore/swift5/frozenEnums/docs/SpecialModelName.md new file mode 100644 index 00000000000..3ec27a38c2a --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/SpecialModelName.md @@ -0,0 +1,10 @@ +# SpecialModelName + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**specialPropertyName** | **Int64** | | [optional] + +[[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/swift5/frozenEnums/docs/StoreAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/StoreAPI.md new file mode 100644 index 00000000000..b023aa9e452 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/StoreAPI.md @@ -0,0 +1,206 @@ +# StoreAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreAPI.md#deleteorder) | **DELETE** /store/order/{order_id} | Delete purchase order by ID +[**getInventory**](StoreAPI.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreAPI.md#getorderbyid) | **GET** /store/order/{order_id} | Find purchase order by ID +[**placeOrder**](StoreAPI.md#placeorder) | **POST** /store/order | Place an order for a pet + + +# **deleteOrder** +```swift + open class func deleteOrder(orderId: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = "orderId_example" // String | ID of the order that needs to be deleted + +// Delete purchase order by ID +StoreAPI.deleteOrder(orderId: orderId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String** | ID of the order that needs to be deleted | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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) + +# **getInventory** +```swift + open class func getInventory(completion: @escaping (_ data: [String: Int]?, _ error: Error?) -> Void) +``` + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Returns pet inventories by status +StoreAPI.getInventory() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**[String: Int]** + +### 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) + +# **getOrderById** +```swift + open class func getOrderById(orderId: Int64, completion: @escaping (_ data: Order?, _ error: Error?) -> Void) +``` + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let orderId = 987 // Int64 | ID of pet that needs to be fetched + +// Find purchase order by ID +StoreAPI.getOrderById(orderId: orderId) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Int64** | ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, 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) + +# **placeOrder** +```swift + open class func placeOrder(body: Order, completion: @escaping (_ data: Order?, _ error: Error?) -> Void) +``` + +Place an order for a pet + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = Order(id: 123, petId: 123, quantity: 123, shipDate: Date(), status: "status_example", complete: false) // Order | order placed for purchasing the pet + +// Place an order for a pet +StoreAPI.placeOrder(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md) | order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, 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/client/petstore/swift5/frozenEnums/docs/StringBooleanMap.md b/samples/client/petstore/swift5/frozenEnums/docs/StringBooleanMap.md new file mode 100644 index 00000000000..7abf11ec68b --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/StringBooleanMap.md @@ -0,0 +1,9 @@ +# StringBooleanMap + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +[[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/swift5/frozenEnums/docs/Tag.md b/samples/client/petstore/swift5/frozenEnums/docs/Tag.md new file mode 100644 index 00000000000..ff4ac8aa451 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/Tag.md @@ -0,0 +1,11 @@ +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**name** | **String** | | [optional] + +[[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/swift5/frozenEnums/docs/TypeHolderDefault.md b/samples/client/petstore/swift5/frozenEnums/docs/TypeHolderDefault.md new file mode 100644 index 00000000000..5161394bdc3 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/TypeHolderDefault.md @@ -0,0 +1,14 @@ +# TypeHolderDefault + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | [default to "what"] +**numberItem** | **Double** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | [default to true] +**arrayItem** | **[Int]** | | + +[[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/swift5/frozenEnums/docs/TypeHolderExample.md b/samples/client/petstore/swift5/frozenEnums/docs/TypeHolderExample.md new file mode 100644 index 00000000000..46d0471cd71 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/TypeHolderExample.md @@ -0,0 +1,14 @@ +# TypeHolderExample + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**stringItem** | **String** | | +**numberItem** | **Double** | | +**integerItem** | **Int** | | +**boolItem** | **Bool** | | +**arrayItem** | **[Int]** | | + +[[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/swift5/frozenEnums/docs/User.md b/samples/client/petstore/swift5/frozenEnums/docs/User.md new file mode 100644 index 00000000000..5a439de0ff9 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/User.md @@ -0,0 +1,17 @@ +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Int64** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Int** | User Status | [optional] + +[[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/swift5/frozenEnums/docs/UserAPI.md b/samples/client/petstore/swift5/frozenEnums/docs/UserAPI.md new file mode 100644 index 00000000000..5fc9160daf4 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/docs/UserAPI.md @@ -0,0 +1,406 @@ +# UserAPI + +All URIs are relative to *http://petstore.swagger.io:80/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserAPI.md#createuser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserAPI.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserAPI.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserAPI.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserAPI.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserAPI.md#loginuser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserAPI.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserAPI.md#updateuser) | **PUT** /user/{username} | Updated user + + +# **createUser** +```swift + open class func createUser(body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Create user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Created user object + +// Create user +UserAPI.createUser(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md) | Created user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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) + +# **createUsersWithArrayInput** +```swift + open class func createUsersWithArrayInput(body: [User], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithArrayInput(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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) + +# **createUsersWithListInput** +```swift + open class func createUsersWithListInput(body: [User], completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Creates list of users with given input array + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let body = [User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123)] // [User] | List of user object + +// Creates list of users with given input array +UserAPI.createUsersWithListInput(body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**[User]**](User.md) | List of user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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) + +# **deleteUser** +```swift + open class func deleteUser(username: String, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Delete user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be deleted + +// Delete user +UserAPI.deleteUser(username: username) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The name that needs to be deleted | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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) + +# **getUserByName** +```swift + open class func getUserByName(username: String, completion: @escaping (_ data: User?, _ error: Error?) -> Void) +``` + +Get user by user name + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The name that needs to be fetched. Use user1 for testing. + +// Get user by user name +UserAPI.getUserByName(username: username) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, 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) + +# **loginUser** +```swift + open class func loginUser(username: String, password: String, completion: @escaping (_ data: String?, _ error: Error?) -> Void) +``` + +Logs user into the system + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | The user name for login +let password = "password_example" // String | The password for login in clear text + +// Logs user into the system +UserAPI.loginUser(username: username, password: password) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | The user name for login | + **password** | **String** | The password for login in clear text | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, 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) + +# **logoutUser** +```swift + open class func logoutUser(completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Logs out current logged in user session + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + + +// Logs out current logged in user session +UserAPI.logoutUser() { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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) + +# **updateUser** +```swift + open class func updateUser(username: String, body: User, completion: @escaping (_ data: Void?, _ error: Error?) -> Void) +``` + +Updated user + +This can only be done by the logged in user. + +### Example +```swift +// The following code samples are still beta. For any issue, please report via http://github.com/OpenAPITools/openapi-generator/issues/new +import PetstoreClient + +let username = "username_example" // String | name that need to be deleted +let body = User(id: 123, username: "username_example", firstName: "firstName_example", lastName: "lastName_example", email: "email_example", password: "password_example", phone: "phone_example", userStatus: 123) // User | Updated user object + +// Updated user +UserAPI.updateUser(username: username, body: body) { (response, error) in + guard error == nil else { + print(error) + return + } + + if (response) { + dump(response) + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String** | name that need to be deleted | + **body** | [**User**](User.md) | Updated user object | + +### Return type + +Void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + +[[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/client/petstore/swift5/frozenEnums/git_push.sh b/samples/client/petstore/swift5/frozenEnums/git_push.sh new file mode 100644 index 00000000000..f53a75d4fab --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/git_push.sh @@ -0,0 +1,57 @@ +#!/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-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/swift5/frozenEnums/pom.xml b/samples/client/petstore/swift5/frozenEnums/pom.xml new file mode 100644 index 00000000000..c1b201eb3b4 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/pom.xml @@ -0,0 +1,43 @@ + + 4.0.0 + io.swagger + Swift5PetstoreClientTests + pom + 1.0-SNAPSHOT + Swift5 Swagger Petstore Client + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + xcodebuild-test + integration-test + + exec + + + ./run_spmbuild.sh + + + + + + + diff --git a/samples/client/petstore/swift5/frozenEnums/project.yml b/samples/client/petstore/swift5/frozenEnums/project.yml new file mode 100644 index 00000000000..0493cf65896 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/project.yml @@ -0,0 +1,15 @@ +name: PetstoreClient +targets: + PetstoreClient: + type: framework + platform: iOS + deploymentTarget: "9.0" + sources: [PetstoreClient] + info: + path: ./Info.plist + version: 1.0.0 + settings: + APPLICATION_EXTENSION_API_ONLY: true + scheme: {} + dependencies: + - carthage: AnyCodable diff --git a/samples/client/petstore/swift5/frozenEnums/run_spmbuild.sh b/samples/client/petstore/swift5/frozenEnums/run_spmbuild.sh new file mode 100755 index 00000000000..1a9f585ad05 --- /dev/null +++ b/samples/client/petstore/swift5/frozenEnums/run_spmbuild.sh @@ -0,0 +1,3 @@ +#!/bin/sh + +swift build && exit ${PIPESTATUS[0]} diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift index 0c1c7548898..60869f63ef6 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + internal enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/swift5_test_all.sh b/samples/client/petstore/swift5/swift5_test_all.sh index f621187c463..faeb4ca6aa1 100755 --- a/samples/client/petstore/swift5/swift5_test_all.sh +++ b/samples/client/petstore/swift5/swift5_test_all.sh @@ -19,6 +19,7 @@ mvn -f $DIRECTORY/alamofireLibrary/pom.xml integration-test mvn -f $DIRECTORY/combineLibrary/pom.xml integration-test mvn -f $DIRECTORY/default/pom.xml integration-test mvn -f $DIRECTORY/deprecated/pom.xml integration-test +mvn -f $DIRECTORY/frozenEnums/pom.xml integration-test mvn -f $DIRECTORY/nonPublicApi/pom.xml integration-test mvn -f $DIRECTORY/objcCompatible/pom.xml integration-test mvn -f $DIRECTORY/oneOf/pom.xml integration-test diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift index ab4165a9b45..7787127c40d 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/Models.swift @@ -14,6 +14,28 @@ extension JSONEncodable { func encodeToJSON() -> Any { self } } +/// An enum where the last case value can be used as a default catch-all. +protocol CaseIterableDefaultsLast: Decodable & CaseIterable & RawRepresentable +where RawValue: Decodable, AllCases: BidirectionalCollection {} + +extension CaseIterableDefaultsLast { + /// Initializes an enum such that if a known raw value is found, then it is decoded. + /// Otherwise the last case is used. + /// - Parameter decoder: A decoder. + public init(from decoder: Decoder) throws { + if let value = try Self(rawValue: decoder.singleValueContainer().decode(RawValue.self)) { + self = value + } else if let lastValue = Self.allCases.last { + self = lastValue + } else { + throw DecodingError.valueNotFound( + Self.Type.self, + .init(codingPath: decoder.codingPath, debugDescription: "CaseIterableDefaultsLast") + ) + } + } +} + public enum ErrorResponse: Error { case error(Int, Data?, URLResponse?, Error) } From 8fc6172c6d1f4bbf47d42123123c82a89f1fc154 Mon Sep 17 00:00:00 2001 From: Tal Kirshboim Date: Sat, 4 Dec 2021 06:06:37 +0100 Subject: [PATCH 51/61] Build and test Kotlin Multiplatform samples in CI (#11023) --- .github/workflows/samples-kotlin.yaml | 3 +-- .../libraries/multiplatform/build.gradle.kts.mustache | 3 +++ samples/client/petstore/kotlin-multiplatform/build.gradle.kts | 3 +++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/samples-kotlin.yaml b/.github/workflows/samples-kotlin.yaml index c6f6f3745c0..d1d812cbadb 100644 --- a/.github/workflows/samples-kotlin.yaml +++ b/.github/workflows/samples-kotlin.yaml @@ -30,8 +30,7 @@ jobs: #- samples/client/petstore/kotlin-json-request-string - samples/client/petstore/kotlin-jvm-okhttp4-coroutines - samples/client/petstore/kotlin-moshi-codegen - # need some special setup - #- samples/client/petstore/kotlin-multiplatform + - samples/client/petstore/kotlin-multiplatform - samples/client/petstore/kotlin-nonpublic - samples/client/petstore/kotlin-nullable - samples/client/petstore/kotlin-okhttp3 diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache index 2a620721ba4..4a09e4daf46 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache @@ -93,4 +93,7 @@ tasks { } } } + register("test") { + dependsOn("allTests") + } } diff --git a/samples/client/petstore/kotlin-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts index 2c891e8fa4f..eb33cf023bf 100644 --- a/samples/client/petstore/kotlin-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts @@ -93,4 +93,7 @@ tasks { } } } + register("test") { + dependsOn("allTests") + } } From 8bc069778f2274eae74493923671ab56f1dabd49 Mon Sep 17 00:00:00 2001 From: jzorn <46689904+jzorn@users.noreply.github.com> Date: Sat, 4 Dec 2021 06:18:06 +0100 Subject: [PATCH 52/61] Compare security schema names case-insensitive (#10989) According to RFC 7235 (HTTP/1.1: Authentication), schema tokens are handled case-insensitive (Section 2.1: Challenge and Response). This change compares the known token values basic, bearer, and signature case-insensitive. - https://datatracker.ietf.org/doc/html/rfc7235#section-2.1 --- .../main/java/org/openapitools/codegen/DefaultCodegen.java | 6 +++--- 1 file changed, 3 insertions(+), 3 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 042ffc089c3..32fdb6058bf 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 @@ -4774,12 +4774,12 @@ public class DefaultCodegen implements CodegenConfig { final CodegenSecurity cs = defaultCodegenSecurity(key, securityScheme); cs.isKeyInHeader = cs.isKeyInQuery = cs.isKeyInCookie = cs.isApiKey = cs.isOAuth = false; cs.isBasic = true; - if ("basic".equals(securityScheme.getScheme())) { + if ("basic".equalsIgnoreCase(securityScheme.getScheme())) { cs.isBasicBasic = true; - } else if ("bearer".equals(securityScheme.getScheme())) { + } else if ("bearer".equalsIgnoreCase(securityScheme.getScheme())) { cs.isBasicBearer = true; cs.bearerFormat = securityScheme.getBearerFormat(); - } else if ("signature".equals(securityScheme.getScheme())) { + } else if ("signature".equalsIgnoreCase(securityScheme.getScheme())) { // HTTP signature as defined in https://datatracker.ietf.org/doc/draft-cavage-http-signatures/ // The registry of security schemes is maintained by IANA. // https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml From 1799e9cd12b41f81ea228fa7992e80e4ca057045 Mon Sep 17 00:00:00 2001 From: WILLIAM CHENG Date: Sat, 4 Dec 2021 13:18:29 +0800 Subject: [PATCH 53/61] update doc --- docs/generators.md | 2 +- docs/generators/swift5.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/generators.md b/docs/generators.md index 088acf1b859..8d8433cd23f 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -85,8 +85,8 @@ The following generators are available: * [cpp-pistache-server](generators/cpp-pistache-server.md) * [cpp-qt-qhttpengine-server](generators/cpp-qt-qhttpengine-server.md) * [cpp-restbed-server](generators/cpp-restbed-server.md) -* [csharp-netcore-functions](generators/csharp-netcore-functions.md) * [csharp-nancyfx](generators/csharp-nancyfx.md) +* [csharp-netcore-functions](generators/csharp-netcore-functions.md) * [erlang-server](generators/erlang-server.md) * [fsharp-functions (beta)](generators/fsharp-functions.md) * [fsharp-giraffe-server (beta)](generators/fsharp-giraffe-server.md) diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index ddcb3bc3db0..9404a2fd458 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -11,7 +11,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |apiNamePrefix|Prefix that will be appended to all API names ('tags'). Default: empty string. e.g. Pet => Pet.| |null| |disallowAdditionalPropertiesIfNotPresent|If false, the 'additionalProperties' implementation (set to true by default) is compliant with the OAS and JSON schema specifications. If true (default), keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.|
    **false**
    The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
    **true**
    Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
    |true| |ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| -|generateFrozenEnums|Generate model enums that are "frozen". A frozen enum strictly represents the cases described in the spec, and nothing else. A non-frozen enum includes an unknown case that can represent future cases not yet described in the spec. (default: true)| |true| +|generateFrozenEnums|Generate frozen enums (default: true)| |true| |generateModelAdditionalProperties|Generate model additional properties (default: true)| |true| |hashableModels|Make hashable models (default: true)| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| From 85985e8bfb62639fed92d3181f0b7da642b09d93 Mon Sep 17 00:00:00 2001 From: Peter Leibiger Date: Sat, 4 Dec 2021 07:31:55 +0100 Subject: [PATCH 54/61] [dart][dio] Fix int64 based enums not correctly generated (#11014) --- .../dart/libraries/dio/serialization/built_value/enum.mustache | 2 +- .../dio/serialization/built_value/enum_inline.mustache | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum.mustache index e3cc6755362..0668b2e7b1d 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum.mustache @@ -11,7 +11,7 @@ class {{classname}} extends EnumClass { {{#description}} /// {{{.}}} {{/description}} - @BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{^isInteger}}wireName: r{{{value}}}{{/isInteger}}) + @BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{#isLong}}wireNumber: {{{value}}}{{/isLong}}{{^isInteger}}{{^isLong}}wireName: r{{{value}}}{{/isLong}}{{/isInteger}}) static const {{classname}} {{name}} = _${{name}}; {{/enumVars}} {{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum_inline.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum_inline.mustache index 5f5dfd49913..c6452b7f6f5 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum_inline.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/enum_inline.mustache @@ -5,7 +5,7 @@ class {{{enumName}}} extends EnumClass { {{#description}} /// {{{.}}} {{/description}} - @BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{^isInteger}}wireName: r{{{value}}}{{/isInteger}}) + @BuiltValueEnumConst({{#isInteger}}wireNumber: {{{value}}}{{/isInteger}}{{#isLong}}wireNumber: {{{value}}}{{/isLong}}{{^isInteger}}{{^isLong}}wireName: r{{{value}}}{{/isLong}}{{/isInteger}}) static const {{{enumName}}} {{name}} = _${{#lambda.camelcase}}{{{enumName}}}{{/lambda.camelcase}}_{{name}}; {{/enumVars}} {{/allowableValues}} From ecddd4cff1e75667ea490b1d9b009e0ad285b97b Mon Sep 17 00:00:00 2001 From: Peter Leibiger Date: Sat, 4 Dec 2021 07:32:36 +0100 Subject: [PATCH 55/61] [dart][dio][built_value] Fix missing serializer factory builders for additionalProperties (#11011) Refactor the addition of custom serializer factories. --- .../languages/AbstractDartCodegen.java | 6 +- .../languages/DartDioNextClientCodegen.java | 110 +++++++++++++++--- .../built_value/serializers.mustache | 12 +- .../lib/src/serializers.dart | 20 ++-- .../lib/src/serializers.dart | 20 ++-- 5 files changed, 121 insertions(+), 47 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java index 86af0181b3d..75e466165a5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java @@ -505,7 +505,7 @@ public abstract class AbstractDartCodegen extends DefaultCodegen { super.postProcessModelProperty(model, property); if (!model.isEnum && property.isEnum) { // These are inner enums, enums which do not exist as models, just as properties. - // They are handled via the enum_inline template and and are generated in the + // They are handled via the enum_inline template and are generated in the // same file as the containing class. To prevent name clashes the inline enum classes // are prefix with the classname of the containing class in the template. // Here the datatypeWithEnum template variable gets updated to match that scheme. @@ -529,9 +529,9 @@ public abstract class AbstractDartCodegen extends DefaultCodegen { public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { final CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); for (CodegenResponse r : op.responses) { - // By default only set types are automatically added to operation imports, not sure why. + // By default, only set types are automatically added to operation imports, not sure why. // Add all container type imports here, by default 'dart:core' imports are skipped - // but other sub classes may required specific container type imports. + // but other sub-classes may require specific container type imports. if (r.containerType != null && typeMapping().containsKey(r.containerType)) { final String value = typeMapping().get(r.containerType); if (needToImport(value)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java index 9acfe364003..5f438eb6f8b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/DartDioNextClientCodegen.java @@ -323,6 +323,21 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { // enums are generated with built_value and make use of BuiltSet model.imports.add("BuiltSet"); } + + if (property.isContainer) { + // Figure out if there are any container type additionalProperties + // that need a custom serializer builder factory added. + final CodegenProperty items = property.items; + if (items.getAdditionalProperties() != null) { + addBuiltValueSerializer(new BuiltValueSerializer( + items.isArray, + items.getUniqueItems(), + items.isMap, + items.items.isNullable, + items.getAdditionalProperties().dataType + )); + } + } } } @@ -332,7 +347,6 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { Map operations = (Map) objs.get("operations"); List operationList = (List) operations.get("operation"); - Set> serializers = new HashSet<>(); Set resultImports = new HashSet<>(); for (CodegenOperation op : operationList) { @@ -370,12 +384,13 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { // Generate serializer factories for all container type parameters. // But skip binary and file parameters, JSON serializers don't make sense there. if (param.isContainer && !(param.isBinary || param.isFile )) { - final Map serializer = new HashMap<>(); - serializer.put("isArray", param.isArray); - serializer.put("uniqueItems", param.uniqueItems); - serializer.put("isMap", param.isMap); - serializer.put("baseType", param.baseType); - serializers.add(serializer); + addBuiltValueSerializer(new BuiltValueSerializer( + param.isArray, + param.uniqueItems, + param.isMap, + param.items.isNullable, + param.baseType + )); } } @@ -387,17 +402,17 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { // Generate serializer factories for response types. // But skip binary and file response, JSON serializers don't make sense there. if (op.returnContainer != null && !(op.isResponseBinary || op.isResponseFile)) { - final Map serializer = new HashMap<>(); - serializer.put("isArray", Objects.equals("array", op.returnContainer) || Objects.equals("set", op.returnContainer)); - serializer.put("uniqueItems", op.uniqueItems); - serializer.put("isMap", Objects.equals("map", op.returnContainer)); - serializer.put("baseType", op.returnBaseType); - serializers.add(serializer); + addBuiltValueSerializer(new BuiltValueSerializer( + Objects.equals("array", op.returnContainer) || Objects.equals("set", op.returnContainer), + op.uniqueItems, + Objects.equals("map", op.returnContainer), + false, + op.returnBaseType + )); } } objs.put("imports", resultImports.stream().sorted().collect(Collectors.toList())); - objs.put("serializers", serializers); return objs; } @@ -410,6 +425,19 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { }); } + /** + * Adds the serializer to the global list of custom built_value serializers. + * @param serializer + */ + private void addBuiltValueSerializer(BuiltValueSerializer serializer) { + System.out.println("######## Add serializer!"); + additionalProperties.compute("builtValueSerializers", (k, v) -> { + Set serializers = v == null ? Sets.newHashSet() : ((Set) v); + serializers.add(serializer); + return serializers; + }); + } + private Set rewriteImports(Set originalImports, boolean isModel) { Set resultImports = Sets.newHashSet(); for (String modelImport : originalImports) { @@ -428,4 +456,58 @@ public class DartDioNextClientCodegen extends AbstractDartCodegen { } return resultImports; } + + static class BuiltValueSerializer { + + final boolean isArray; + + final boolean uniqueItems; + + final boolean isMap; + + final boolean isNullable; + + final String dataType; + + private BuiltValueSerializer(boolean isArray, boolean uniqueItems, boolean isMap, boolean isNullable, String dataType) { + this.isArray = isArray; + this.uniqueItems = uniqueItems; + this.isMap = isMap; + this.isNullable = isNullable; + this.dataType = dataType; + } + + public boolean isArray() { + return isArray; + } + + public boolean isUniqueItems() { + return uniqueItems; + } + + public boolean isMap() { + return isMap; + } + + public boolean isNullable() { + return isNullable; + } + + public String getDataType() { + return dataType; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + BuiltValueSerializer that = (BuiltValueSerializer) o; + return isArray == that.isArray && uniqueItems == that.uniqueItems && isMap == that.isMap && isNullable == that.isNullable && dataType.equals(that.dataType); + } + + @Override + public int hashCode() { + return Objects.hash(isArray, uniqueItems, isMap, isNullable, dataType); + } + } } diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache index e1f3dbe1df5..c558f153c89 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/built_value/serializers.mustache @@ -19,17 +19,17 @@ part 'serializers.g.dart'; @SerializersFor([{{#models}}{{#model}} {{classname}},{{/model}}{{/models}} ]) -Serializers serializers = (_$serializers.toBuilder(){{#apiInfo}}{{#apis}}{{#serializers}} +Serializers serializers = (_$serializers.toBuilder(){{#builtValueSerializers}} ..addBuilderFactory( {{#isArray}} - const FullType(Built{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}, [FullType({{baseType}})]), - () => {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}Builder<{{baseType}}>(), + const FullType(Built{{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}, [FullType{{#isNullable}}.nullable{{/isNullable}}({{dataType}})]), + () => {{#uniqueItems}}Set{{/uniqueItems}}{{^uniqueItems}}List{{/uniqueItems}}Builder<{{dataType}}>(), {{/isArray}} {{#isMap}} - const FullType(BuiltMap, [FullType(String), FullType({{baseType}})]), - () => MapBuilder(), + const FullType(BuiltMap, [FullType(String), FullType{{#isNullable}}.nullable{{/isNullable}}({{dataType}})]), + () => MapBuilder(), {{/isMap}} - ){{/serializers}}{{/apis}}{{/apiInfo}}{{#useDateLibTimeMachine}} + ){{/builtValueSerializers}}{{#useDateLibTimeMachine}} ..add(const OffsetDateSerializer()) ..add(const OffsetDateTimeSerializer()){{/useDateLibTimeMachine}}{{#useDateLibCore}} ..add(const DateSerializer()) diff --git a/samples/openapi3/client/petstore/dart-dio-next/dio_http_petstore_client_lib_fake/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio-next/dio_http_petstore_client_lib_fake/lib/src/serializers.dart index 1b807addf9e..5ee82d7b501 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/dio_http_petstore_client_lib_fake/lib/src/serializers.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/dio_http_petstore_client_lib_fake/lib/src/serializers.dart @@ -110,26 +110,22 @@ part 'serializers.g.dart'; User, ]) Serializers serializers = (_$serializers.toBuilder() - ..addBuilderFactory( - const FullType(BuiltList, [FullType(String)]), - () => ListBuilder(), - ) ..addBuilderFactory( const FullType(BuiltMap, [FullType(String), FullType(String)]), () => MapBuilder(), ) ..addBuilderFactory( - const FullType(BuiltList, [FullType(String)]), - () => ListBuilder(), - ) - ..addBuilderFactory( - const FullType(BuiltSet, [FullType(Pet)]), - () => SetBuilder(), + const FullType(BuiltList, [FullType(User)]), + () => ListBuilder(), ) ..addBuilderFactory( const FullType(BuiltSet, [FullType(String)]), () => SetBuilder(), ) + ..addBuilderFactory( + const FullType(BuiltSet, [FullType(Pet)]), + () => SetBuilder(), + ) ..addBuilderFactory( const FullType(BuiltList, [FullType(Pet)]), () => ListBuilder(), @@ -139,8 +135,8 @@ Serializers serializers = (_$serializers.toBuilder() () => MapBuilder(), ) ..addBuilderFactory( - const FullType(BuiltList, [FullType(User)]), - () => ListBuilder(), + const FullType(BuiltList, [FullType(String)]), + () => ListBuilder(), ) ..add(const DateSerializer()) ..add(Iso8601DateTimeSerializer())) diff --git a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart index 1b807addf9e..5ee82d7b501 100644 --- a/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart +++ b/samples/openapi3/client/petstore/dart-dio-next/petstore_client_lib_fake/lib/src/serializers.dart @@ -110,26 +110,22 @@ part 'serializers.g.dart'; User, ]) Serializers serializers = (_$serializers.toBuilder() - ..addBuilderFactory( - const FullType(BuiltList, [FullType(String)]), - () => ListBuilder(), - ) ..addBuilderFactory( const FullType(BuiltMap, [FullType(String), FullType(String)]), () => MapBuilder(), ) ..addBuilderFactory( - const FullType(BuiltList, [FullType(String)]), - () => ListBuilder(), - ) - ..addBuilderFactory( - const FullType(BuiltSet, [FullType(Pet)]), - () => SetBuilder(), + const FullType(BuiltList, [FullType(User)]), + () => ListBuilder(), ) ..addBuilderFactory( const FullType(BuiltSet, [FullType(String)]), () => SetBuilder(), ) + ..addBuilderFactory( + const FullType(BuiltSet, [FullType(Pet)]), + () => SetBuilder(), + ) ..addBuilderFactory( const FullType(BuiltList, [FullType(Pet)]), () => ListBuilder(), @@ -139,8 +135,8 @@ Serializers serializers = (_$serializers.toBuilder() () => MapBuilder(), ) ..addBuilderFactory( - const FullType(BuiltList, [FullType(User)]), - () => ListBuilder(), + const FullType(BuiltList, [FullType(String)]), + () => ListBuilder(), ) ..add(const DateSerializer()) ..add(Iso8601DateTimeSerializer())) From 96ee13bbb2e261bd42096ebf709d735afd8902a5 Mon Sep 17 00:00:00 2001 From: WILLIAM CHENG Date: Sat, 4 Dec 2021 14:43:32 +0800 Subject: [PATCH 56/61] replace tab with spaces --- .../CsharpNetcoreFunctionsServerCodegen.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java index fb99c5a149a..f2ab9939c34 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java @@ -39,10 +39,10 @@ public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedCli embeddedTemplateDir = templateDir = "csharp-netcore-functions"; apiPackage = "Apis"; modelPackage = "Models"; - String clientPackageDir = "generatedSrc/Client"; + String clientPackageDir = "generatedSrc/Client"; supportingFiles.add(new SupportingFile("README.mustache", "generatedSrc", "README.md")); supportingFiles.add(new SupportingFile("project.mustache", "generatedSrc", "project.json")); - + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); supportingFiles.add(new SupportingFile("Configuration.mustache", @@ -58,13 +58,13 @@ public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedCli supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs")); } - - @Override + + @Override public String apiFileFolder() { return outputFolder + File.separator + "generatedSrc" + File.separator + "Functions"; } - - @Override + + @Override public String modelFileFolder() { return outputFolder + File.separator + "generatedSrc" + File.separator + "Models"; } From 03b4ac736f0b686f8ecd3a873447873dec4a5c28 Mon Sep 17 00:00:00 2001 From: Alexey Makhrov Date: Sat, 4 Dec 2021 08:43:52 -0800 Subject: [PATCH 57/61] [typescript-angular] taggedUnions=true: Support recursive schemas (#11016) * typescript-angular: taggedUnions=true: Preserve import to the parent model from the child if the child property has a direct reference to it * Fix javadoc --- .../openapitools/codegen/DefaultCodegen.java | 60 +++++++++++++------ .../TypeScriptAngularClientCodegen.java | 11 ++++ .../TypeScriptAngularClientCodegenTest.java | 52 ++++++++++++++-- ...f_composition_discriminator_recursive.yaml | 51 ++++++++++++++++ 4 files changed, 151 insertions(+), 23 deletions(-) create mode 100644 modules/openapi-generator/src/test/resources/3_0/allOf_composition_discriminator_recursive.yaml 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 32fdb6058bf..f1736f0e532 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 @@ -570,14 +570,7 @@ public class DefaultCodegen implements CodegenConfig { List> models = (List>) inner.get("models"); for (Map mo : models) { CodegenModel cm = (CodegenModel) mo.get("model"); - for (CodegenProperty cp : cm.allVars) { - // detect self import - if (cp.dataType.equalsIgnoreCase(cm.classname) || - (cp.isContainer && cp.items != null && cp.items.dataType.equalsIgnoreCase(cm.classname))) { - cm.imports.remove(cm.classname); // remove self import - cp.isSelfReference = true; - } - } + removeSelfReferenceImports(cm); } } setCircularReferences(allModels); @@ -585,6 +578,23 @@ public class DefaultCodegen implements CodegenConfig { return objs; } + /** + * Removes imports from the model that points to itself + * Marks a self referencing property, if detected + * + * @param model Self imports will be removed from this model.imports collection + */ + protected void removeSelfReferenceImports(CodegenModel model) { + for (CodegenProperty cp : model.allVars) { + // detect self import + if (cp.dataType.equalsIgnoreCase(model.classname) || + (cp.isContainer && cp.items != null && cp.items.dataType.equalsIgnoreCase(model.classname))) { + model.imports.remove(model.classname); // remove self import + cp.isSelfReference = true; + } + } + } + public void setCircularReferences(Map models) { final Map> dependencyMap = models.entrySet().stream() .collect(Collectors.toMap(Entry::getKey, entry -> getModelDependencies(entry.getValue()))); @@ -5168,17 +5178,7 @@ public class DefaultCodegen implements CodegenConfig { cm.hasOnlyReadOnly = false; } - // TODO revise the logic to include map - if (cp.isContainer) { - addImport(cm, typeMapping.get("array")); - } - - addImport(cm, cp.baseType); - CodegenProperty innerCp = cp; - while (innerCp != null) { - addImport(cm, innerCp.complexType); - innerCp = innerCp.items; - } + addImportsForPropertyType(cm, cp); // if required, add to the list "requiredVars" if (Boolean.TRUE.equals(cp.required)) { @@ -5199,6 +5199,28 @@ public class DefaultCodegen implements CodegenConfig { return; } + /** + * For a given property, adds all needed imports to the model + * This includes a flat property type (e.g. property type: ReferencedModel) + * as well as container type (property type: array of ReferencedModel's) + * + * @param model The codegen representation of the OAS schema. + * @param property The codegen representation of the OAS schema's property. + */ + protected void addImportsForPropertyType(CodegenModel model, CodegenProperty property) { + // TODO revise the logic to include map + if (property.isContainer) { + addImport(model, typeMapping.get("array")); + } + + addImport(model, property.baseType); + CodegenProperty innerCp = property; + while (innerCp != null) { + addImport(model, innerCp.complexType); + innerCp = innerCp.items; + } + } + /** * Determine all of the types in the model definitions (schemas) that are aliases of * simple types. diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java index 858e33d0c53..d2ab116ab1e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptAngularClientCodegen.java @@ -549,8 +549,19 @@ public class TypeScriptAngularClientCodegen extends AbstractTypeScriptClientCode setChildDiscriminatorValue(cm, child); } } + + // with tagged union, a child model doesn't extend the parent (all properties are just copied over) + // it means we don't need to import that parent any more if (cm.parent != null) { cm.imports.remove(cm.parent); + + // however, it's possible that the child model contains a recursive reference to the parent + // in order to support this case, we update the list of imports from properties once again + for (CodegenProperty cp: cm.allVars) { + addImportsForPropertyType(cm, cp); + } + removeSelfReferenceImports(cm); + } } // Add additional filename information for imports diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java index e5a76bd02a3..61231472997 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/typescript/typescriptangular/TypeScriptAngularClientCodegenTest.java @@ -8,14 +8,18 @@ import io.swagger.v3.oas.models.media.Schema; import io.swagger.v3.oas.models.media.StringSchema; import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.oas.models.responses.ApiResponses; -import org.openapitools.codegen.CodegenConstants; -import org.openapitools.codegen.CodegenOperation; -import org.openapitools.codegen.CodegenProperty; -import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.config.CodegenConfigurator; import org.openapitools.codegen.languages.TypeScriptAngularClientCodegen; import org.testng.Assert; import org.testng.annotations.Test; +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; + public class TypeScriptAngularClientCodegenTest { @Test @@ -267,4 +271,44 @@ public class TypeScriptAngularClientCodegenTest { codegen.importMapping().put(importedModel, importName); Assert.assertEquals(codegen.toModelImport(importedModel), importName); } + + @Test + public void testTaggedUnionImports() throws Exception { + final String specPath = "src/test/resources/3_0/allOf_composition_discriminator_recursive.yaml"; + + Map properties = new HashMap<>(); + properties.put(TypeScriptAngularClientCodegen.TAGGED_UNIONS, "true"); + + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("typescript-angular") + .setInputSpec(specPath) + .setAdditionalProperties(properties) + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + + Generator generator = new DefaultGenerator(); + generator.opts(clientOptInput).generate(); + + TestUtils.assertFileContains( + Paths.get(output + "/model/expressionToken.ts"), + "import { Token } from './token'", // imports the parent schema + "import { TokenMetadata } from './tokenMetadata'", // imports a schema referenced in an inherited property + "export interface ExpressionToken {" // no inheritance + ); + + TestUtils.assertFileNotContains( + Paths.get(output + "/model/stringToken.ts"), + "import { Token } from './token'" + ); + + TestUtils.assertFileContains( + Paths.get(output + "/model/token.ts"), + "import { ExpressionToken } from './expressionToken'", + "export type Token = ExpressionToken | StringToken" + ); + } } diff --git a/modules/openapi-generator/src/test/resources/3_0/allOf_composition_discriminator_recursive.yaml b/modules/openapi-generator/src/test/resources/3_0/allOf_composition_discriminator_recursive.yaml new file mode 100644 index 00000000000..de3b9f21177 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/allOf_composition_discriminator_recursive.yaml @@ -0,0 +1,51 @@ +openapi: 3.0.2 +info: + title: OAI Specification example for Polymorphism + version: 1.0.0 +paths: + /status: + get: + responses: + '201': + description: desc + +components: + schemas: + TokenMetadata: + type: object + properties: + tag1: + type: string + + Token: + type: object + required: + - type + properties: + type: + type: string + metadata: + $ref: '#/components/schemas/TokenMetadata' + discriminator: + propertyName: type + mapping: + string: '#/components/schemas/StringToken' + expression: '#/components/schemas/ExpressionToken' + + StringToken: + allOf: + - $ref: '#/components/schemas/Token' + - type: object + properties: + value: + type: string + + ExpressionToken: + allOf: + - $ref: '#/components/schemas/Token' + - type: object + properties: + tokens: + type: array + items: + $ref: '#/components/schemas/Token' \ No newline at end of file From 186842ea197bf914cc16345643126d7e25699856 Mon Sep 17 00:00:00 2001 From: Yuriy Belenko Date: Sun, 5 Dec 2021 10:47:12 +0300 Subject: [PATCH 58/61] [php-slim4] Bump required PHP version to 7.4 (#11039) * Change minimum PHP version to 7.4 * Refresh samples --- .../src/main/resources/php-slim4-server/README.mustache | 2 +- .../src/main/resources/php-slim4-server/composer.mustache | 2 +- .../src/main/resources/php-slim4-server/licenseInfo.mustache | 2 +- samples/server/petstore/php-slim4/README.md | 2 +- samples/server/petstore/php-slim4/composer.json | 2 +- samples/server/petstore/php-slim4/config/dev/example.inc.php | 2 +- samples/server/petstore/php-slim4/config/prod/example.inc.php | 2 +- samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php | 2 +- samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php | 2 +- samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php | 2 +- .../petstore/php-slim4/lib/Auth/AbstractAuthenticator.php | 2 +- samples/server/petstore/php-slim4/lib/BaseModel.php | 2 +- .../php-slim4/lib/Middleware/JsonBodyParserMiddleware.php | 2 +- samples/server/petstore/php-slim4/lib/Model/ApiResponse.php | 2 +- samples/server/petstore/php-slim4/lib/Model/Category.php | 2 +- samples/server/petstore/php-slim4/lib/Model/Order.php | 2 +- samples/server/petstore/php-slim4/lib/Model/Pet.php | 2 +- samples/server/petstore/php-slim4/lib/Model/Tag.php | 2 +- samples/server/petstore/php-slim4/lib/Model/User.php | 2 +- samples/server/petstore/php-slim4/lib/SlimRouter.php | 2 +- samples/server/petstore/php-slim4/public/index.php | 2 +- samples/server/petstore/php-slim4/tests/BaseModelTest.php | 2 +- 22 files changed, 22 insertions(+), 22 deletions(-) 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 0a5ecca3d6b..9435bf7f24a 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 @@ -19,7 +19,7 @@ This server has been generated with [Laminas (Zend) PSR-7 implementation](https: ## Requirements * Web server with URL rewriting -* PHP 7.3 or newer +* PHP 7.4 or newer This package contains `.htaccess` for Apache configuration. If you use another server(Nginx, HHVM, IIS, lighttpd) check out [Web Servers](https://www.slimframework.com/docs/v3/start/web-servers.html) doc. diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache index 4375a02d56a..803a0c140cd 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/composer.mustache @@ -8,7 +8,7 @@ } ], "require": { - "php": "^7.3 || ^8.0", + "php": "^7.4 || ^8.0", "slim/slim": "^4.5.0", "dyorg/slim-token-authentication": "dev-slim4", "ybelenko/openapi-data-mocker": "^1.0", diff --git a/modules/openapi-generator/src/main/resources/php-slim4-server/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/php-slim4-server/licenseInfo.mustache index b3278a2920e..8a61a5402ff 100644 --- a/modules/openapi-generator/src/main/resources/php-slim4-server/licenseInfo.mustache +++ b/modules/openapi-generator/src/main/resources/php-slim4-server/licenseInfo.mustache @@ -2,7 +2,7 @@ {{#appName}} * {{{.}}} {{/appName}} - * PHP version 7.3 + * PHP version 7.4 * * @package {{invokerPackage}} * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/README.md b/samples/server/petstore/php-slim4/README.md index 5dc80231b17..ac51de45d1e 100644 --- a/samples/server/petstore/php-slim4/README.md +++ b/samples/server/petstore/php-slim4/README.md @@ -8,7 +8,7 @@ This server has been generated with [Slim PSR-7](https://github.com/slimphp/Slim ## Requirements * Web server with URL rewriting -* PHP 7.3 or newer +* PHP 7.4 or newer This package contains `.htaccess` for Apache configuration. If you use another server(Nginx, HHVM, IIS, lighttpd) check out [Web Servers](https://www.slimframework.com/docs/v3/start/web-servers.html) doc. diff --git a/samples/server/petstore/php-slim4/composer.json b/samples/server/petstore/php-slim4/composer.json index da7b26a6d4f..529f8f93715 100644 --- a/samples/server/petstore/php-slim4/composer.json +++ b/samples/server/petstore/php-slim4/composer.json @@ -8,7 +8,7 @@ } ], "require": { - "php": "^7.3 || ^8.0", + "php": "^7.4 || ^8.0", "slim/slim": "^4.5.0", "dyorg/slim-token-authentication": "dev-slim4", "ybelenko/openapi-data-mocker": "^1.0", diff --git a/samples/server/petstore/php-slim4/config/dev/example.inc.php b/samples/server/petstore/php-slim4/config/dev/example.inc.php index 9d461dca380..2a2e65d4a59 100644 --- a/samples/server/petstore/php-slim4/config/dev/example.inc.php +++ b/samples/server/petstore/php-slim4/config/dev/example.inc.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/config/prod/example.inc.php b/samples/server/petstore/php-slim4/config/prod/example.inc.php index 9d461dca380..2a2e65d4a59 100644 --- a/samples/server/petstore/php-slim4/config/prod/example.inc.php +++ b/samples/server/petstore/php-slim4/config/prod/example.inc.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php index 3565cbc42c6..ff8c7224526 100644 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php +++ b/samples/server/petstore/php-slim4/lib/Api/AbstractPetApi.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php index af982bec785..2542047a669 100644 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php +++ b/samples/server/petstore/php-slim4/lib/Api/AbstractStoreApi.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php b/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php index ee99c33e8ae..eee2c7d2ccf 100644 --- a/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php +++ b/samples/server/petstore/php-slim4/lib/Api/AbstractUserApi.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php b/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php index 42ea8a34d49..de2e6011364 100644 --- a/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php +++ b/samples/server/petstore/php-slim4/lib/Auth/AbstractAuthenticator.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/BaseModel.php b/samples/server/petstore/php-slim4/lib/BaseModel.php index a8330177973..b0040c1a557 100644 --- a/samples/server/petstore/php-slim4/lib/BaseModel.php +++ b/samples/server/petstore/php-slim4/lib/BaseModel.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Middleware/JsonBodyParserMiddleware.php b/samples/server/petstore/php-slim4/lib/Middleware/JsonBodyParserMiddleware.php index 993224f6c87..b1199ffd84a 100644 --- a/samples/server/petstore/php-slim4/lib/Middleware/JsonBodyParserMiddleware.php +++ b/samples/server/petstore/php-slim4/lib/Middleware/JsonBodyParserMiddleware.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/ApiResponse.php b/samples/server/petstore/php-slim4/lib/Model/ApiResponse.php index 6368eb2c726..bd0edc18f10 100644 --- a/samples/server/petstore/php-slim4/lib/Model/ApiResponse.php +++ b/samples/server/petstore/php-slim4/lib/Model/ApiResponse.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/Category.php b/samples/server/petstore/php-slim4/lib/Model/Category.php index 8e1c6e1b653..584fe5d7d3b 100644 --- a/samples/server/petstore/php-slim4/lib/Model/Category.php +++ b/samples/server/petstore/php-slim4/lib/Model/Category.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/Order.php b/samples/server/petstore/php-slim4/lib/Model/Order.php index 52dfff78c0a..1422e6efcf4 100644 --- a/samples/server/petstore/php-slim4/lib/Model/Order.php +++ b/samples/server/petstore/php-slim4/lib/Model/Order.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/Pet.php b/samples/server/petstore/php-slim4/lib/Model/Pet.php index c400e3208de..f249c10dfac 100644 --- a/samples/server/petstore/php-slim4/lib/Model/Pet.php +++ b/samples/server/petstore/php-slim4/lib/Model/Pet.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/Tag.php b/samples/server/petstore/php-slim4/lib/Model/Tag.php index 4606b83ae88..81d7a6e26a6 100644 --- a/samples/server/petstore/php-slim4/lib/Model/Tag.php +++ b/samples/server/petstore/php-slim4/lib/Model/Tag.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/Model/User.php b/samples/server/petstore/php-slim4/lib/Model/User.php index 5fb9f025cd0..68494ec67b5 100644 --- a/samples/server/petstore/php-slim4/lib/Model/User.php +++ b/samples/server/petstore/php-slim4/lib/Model/User.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/lib/SlimRouter.php b/samples/server/petstore/php-slim4/lib/SlimRouter.php index fcc1a818d6c..c0b9c2bda9f 100644 --- a/samples/server/petstore/php-slim4/lib/SlimRouter.php +++ b/samples/server/petstore/php-slim4/lib/SlimRouter.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/public/index.php b/samples/server/petstore/php-slim4/public/index.php index 17511cbfb7a..07ab220a086 100644 --- a/samples/server/petstore/php-slim4/public/index.php +++ b/samples/server/petstore/php-slim4/public/index.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team diff --git a/samples/server/petstore/php-slim4/tests/BaseModelTest.php b/samples/server/petstore/php-slim4/tests/BaseModelTest.php index 49927e56871..33325cc198c 100644 --- a/samples/server/petstore/php-slim4/tests/BaseModelTest.php +++ b/samples/server/petstore/php-slim4/tests/BaseModelTest.php @@ -2,7 +2,7 @@ /** * OpenAPI Petstore - * PHP version 7.3 + * PHP version 7.4 * * @package OpenAPIServer * @author OpenAPI Generator team From 5451b77d424d5eb17cb50a94f4efa7737ffd36cc Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 5 Dec 2021 17:43:17 +0800 Subject: [PATCH 59/61] [CodegenResponse] various enhancements and bug fixes (#10984) * add more response tests, fix simpleType * samples update * replace simpleType with containerType * update doc template * fix typo in mustache tag --- .../codegen/CodegenOperation.java | 8 +- .../openapitools/codegen/DefaultCodegen.java | 12 +- .../languages/ElixirClientCodegen.java | 7 +- .../asciidoc-documentation/index.mustache | 2 +- .../main/resources/htmlDocs/index.mustache | 2 +- .../codegen/DefaultCodegenTest.java | 53 ++ .../test/resources/3_0/response-tests.yaml | 571 ++++++++++++++++++ 7 files changed, 643 insertions(+), 12 deletions(-) create mode 100644 modules/openapi-generator/src/test/resources/3_0/response-tests.yaml diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java index ef348bbb266..83413a9ee11 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java @@ -29,7 +29,8 @@ public class CodegenOperation { isArray, isMultipart, isResponseBinary = false, isResponseFile = false, hasReference = false, isRestfulIndex, isRestfulShow, isRestfulCreate, isRestfulUpdate, isRestfulDestroy, - isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false; + isRestful, isDeprecated, isCallbackRequest, uniqueItems, hasDefaultResponse = false, + hasErrorResponseObject; // if 4xx, 5xx repsonses have at least one error object defined public String path, operationId, returnType, returnFormat, httpMethod, returnBaseType, returnContainer, summary, unescapedNotes, notes, baseName, defaultResponse; public CodegenDiscriminator discriminator; @@ -297,6 +298,7 @@ public class CodegenOperation { sb.append(", isResponseFile=").append(isResponseFile); sb.append(", hasReference=").append(hasReference); sb.append(", hasDefaultResponse=").append(hasDefaultResponse); + sb.append(", hasErrorResponseObject=").append(hasErrorResponseObject); sb.append(", isRestfulIndex=").append(isRestfulIndex); sb.append(", isRestfulShow=").append(isRestfulShow); sb.append(", isRestfulCreate=").append(isRestfulCreate); @@ -371,6 +373,7 @@ public class CodegenOperation { isResponseFile == that.isResponseFile && hasReference == that.hasReference && hasDefaultResponse == that.hasDefaultResponse && + hasErrorResponseObject == that.hasErrorResponseObject && isRestfulIndex == that.isRestfulIndex && isRestfulShow == that.isRestfulShow && isRestfulCreate == that.isRestfulCreate && @@ -435,6 +438,7 @@ public class CodegenOperation { produces, prioritizedContentTypes, servers, bodyParam, allParams, bodyParams, pathParams, queryParams, headerParams, formParams, cookieParams, requiredParams, optionalParams, authMethods, tags, responses, callbacks, imports, examples, requestBodyExamples, externalDocs, vendorExtensions, - nickname, operationIdOriginal, operationIdLowerCase, operationIdCamelCase, operationIdSnakeCase); + nickname, operationIdOriginal, operationIdLowerCase, operationIdCamelCase, operationIdSnakeCase, + hasErrorResponseObject); } } 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 f1736f0e532..e97a6caf557 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 @@ -3976,6 +3976,12 @@ public class DefaultCodegen implements CodegenConfig { if (Boolean.TRUE.equals(r.isFile) && Boolean.TRUE.equals(r.is2xx) && Boolean.FALSE.equals(op.isResponseFile)) { op.isResponseFile = Boolean.TRUE; } + + // check if any 4xx or 5xx reponse has an error response object defined + if ((Boolean.TRUE.equals(r.is4xx) || Boolean.TRUE.equals(r.is5xx)) && + Boolean.FALSE.equals(r.primitiveType) && Boolean.FALSE.equals(r.simpleType)) { + op.hasErrorResponseObject = Boolean.TRUE; + } } op.responses.sort((a, b) -> { int aScore = a.isWildcard() ? 2 : a.isRange() ? 1 : 0; @@ -4269,6 +4275,7 @@ public class DefaultCodegen implements CodegenConfig { r.setComposedSchemas(getComposedSchemas(responseSchema)); if (ModelUtils.isArraySchema(responseSchema)) { r.simpleType = false; + r.isArray = true; r.containerType = cp.containerType; ArraySchema as = (ArraySchema) responseSchema; CodegenProperty items = fromProperty("response", getSchemaItems(as)); @@ -4324,6 +4331,8 @@ public class DefaultCodegen implements CodegenConfig { } else if (ModelUtils.isTypeObjectSchema(responseSchema)) { if (ModelUtils.isFreeFormObject(openAPI, responseSchema)) { r.isFreeFormObject = true; + } else { + r.isModel = true; } r.simpleType = false; r.containerType = cp.containerType; @@ -4335,9 +4344,6 @@ public class DefaultCodegen implements CodegenConfig { LOGGER.debug("Property type is not primitive: {}", cp.dataType); } - if (!r.isMap && !r.isArray) { - r.simpleType = true; - } r.primitiveType = (r.baseType == null || languageSpecificPrimitives().contains(r.baseType)); if (r.baseType == null) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java index 9903908d4e0..62c9d6dcc5f 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ElixirClientCodegen.java @@ -613,7 +613,7 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig return "%{}"; } // Primitive return type, don't even try to decode - if (baseType == null || (simpleType && primitiveType)) { + if (baseType == null || (containerType == null && primitiveType)) { return "false"; } else if (isArray && languageSpecificPrimitives().contains(baseType)) { return "[]"; @@ -733,16 +733,13 @@ public class ElixirClientCodegen extends DefaultCodegen implements CodegenConfig StringBuilder returnEntry = new StringBuilder(); if (exResponse.baseType == null) { returnEntry.append("nil"); - } else if (exResponse.simpleType) { + } else if (exResponse.containerType == null) { // not container (array, map, set) if (!exResponse.primitiveType) { returnEntry.append(moduleName); returnEntry.append(".Model."); } returnEntry.append(exResponse.baseType); returnEntry.append(".t"); - } else if (exResponse.containerType == null) { - returnEntry.append(returnBaseType); - returnEntry.append(".t"); } else { if (exResponse.containerType.equals("array") || exResponse.containerType.equals("set")) { diff --git a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache index 48d810d038a..483ee5870f4 100644 --- a/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache +++ b/modules/openapi-generator/src/main/resources/asciidoc-documentation/index.mustache @@ -104,7 +104,7 @@ Operation Id:: {{nickname}} | {{code}} | {{message}} -| {{^simpleType}}{{dataType}}[<<{{baseType}}>>]{{/simpleType}} {{#simpleType}}<<{{dataType}}>>{{/simpleType}} +| {{#containerType}}{{dataType}}[<<{{baseType}}>>]{{/containerType}} {{^containerType}}<<{{dataType}}>>{{/containerType}} {{/responses}} |=== diff --git a/modules/openapi-generator/src/main/resources/htmlDocs/index.mustache b/modules/openapi-generator/src/main/resources/htmlDocs/index.mustache index a5ad68cc9c8..2f3f276c476 100644 --- a/modules/openapi-generator/src/main/resources/htmlDocs/index.mustache +++ b/modules/openapi-generator/src/main/resources/htmlDocs/index.mustache @@ -134,7 +134,7 @@ {{#responses}}

    {{code}}

    {{message}} - {{#simpleType}}{{dataType}}{{/simpleType}} + {{^containerType}}{{dataType}}{{/containerType}} {{#examples}}

    Example data

    Content-Type: {{{contentType}}}
    diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index 87486da4c36..949bc1a9243 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -3877,6 +3877,59 @@ public class DefaultCodegenTest { } @Test + public void testResponses() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/response-tests.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.setOpenAPI(openAPI); + codegen.setDisallowAdditionalPropertiesIfNotPresent(false); + + String path; + Operation operation; + CodegenOperation co; + CodegenParameter cpa; + CodegenResponse cr; + + path = "/pet/{petId}"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + //assertTrue(co.hasErrorResponseObject); + cr = co.responses.get(0); + assertTrue(cr.is2xx); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + cr = co.responses.get(3); + assertTrue(cr.is5xx); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + + path = "/pet"; + operation = openAPI.getPaths().get(path).getPut(); + co = codegen.fromOperation(path, "PUT", operation, null); + assertTrue(co.hasErrorResponseObject); + + // 200 response + cr = co.responses.get(0); + assertTrue(cr.is2xx); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + + // 400 response + cr = co.responses.get(1); + assertTrue(cr.is4xx); + assertEquals(cr.code, "400"); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + + path = "/pet/findByTags"; + operation = openAPI.getPaths().get(path).getGet(); + co = codegen.fromOperation(path, "GET", operation, null); + assertFalse(co.hasErrorResponseObject); + cr = co.responses.get(0); + assertTrue(cr.is2xx); + assertFalse(cr.simpleType); + assertFalse(cr.primitiveType); + } + public void testParameterContent() { DefaultCodegen codegen = new DefaultCodegen(); final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/content-data.yaml"); diff --git a/modules/openapi-generator/src/test/resources/3_0/response-tests.yaml b/modules/openapi-generator/src/test/resources/3_0/response-tests.yaml new file mode 100644 index 00000000000..e17881606db --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/response-tests.yaml @@ -0,0 +1,571 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '500': + description: Server error + content: + application/application: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generated exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + '500': + description: Server error + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string From 5a62ae6628fb30d2fd61c42c8d1961614ea757f1 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Sun, 5 Dec 2021 17:58:55 +0800 Subject: [PATCH 60/61] Add links to blog posts, remove nmuesch remove java tech comm (#11040) * add links to blog posts, remove nmuesch remove java tech comm * fix link --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 7241d3bf309..210de6791d2 100644 --- a/README.md +++ b/README.md @@ -844,6 +844,8 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - 2021-10-02 - [How to Write Fewer Lines of Code with the OpenAPI Generator](https://hackernoon.com/how-to-write-fewer-lines-of-code-with-the-openapi-generator) by [Mikhail Alfa](https://hackernoon.com/u/alphamikle) - 2021-10-12 - [OpenAPI Generator : 4000 étoiles sur GitHub et des spaghettis](https://www.youtube.com/watch?v=9hEsNBSqTFk) by [Jérémie Bresson](https://github.com/jmini) at [Devoxx FR 2021](https://cfp.devoxx.fr/2021/speaker/jeremie_bresson) - 2021-10-17 - [Generate a TypeScript HTTP Client From An OpenAPI Spec In DotNET 5](https://richardwillis.info/blog/generate-a-type-script-http-client-from-an-open-api-spec-in-dot-net-5) by [Richard Willis](https://github.com/badsyntax) +- 2021-11-06 - [スタートアップの開発で意識したこと](https://zenn.dev/woo_noo/articles/5cb09f8e2899ae782ad1) by [woo-noo](https://zenn.dev/woo_noo) +- 2021-11-09 - [Effective Software Development using OpenAPI Generator](https://apexlabs.ai/post/effective-software-development-using-openapi-generator) by Ajil Oomme ## [6 - About Us](#table-of-contents) @@ -1060,7 +1062,7 @@ If you want to join the committee, please kindly apply by sending an email to te | GraphQL | @renepardon (2018/12) | | Groovy | | | Haskell | | -| Java | @bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) @nmuesch (2021/01) | +| Java | @bbdouglas (2017/07) @sreeshas (2017/08) @jfiala (2017/08) @lukoyanov (2017/09) @cbornet (2017/09) @jeff9finger (2018/01) @karismann (2019/03) @Zomzog (2019/04) @lwlee2608 (2019/10) | | JMeter | @kannkyo (2021/01) | | Kotlin | @jimschubert (2017/09) [:heart:](https://www.patreon.com/jimschubert), @dr4ke616 (2018/08) @karismann (2019/03) @Zomzog (2019/04) @andrewemery (2019/10) @4brunu (2019/11) @yutaka0m (2020/03) | | Lua | @daurnimator (2017/08) | From 95377f68bfa1e054097ddafc62548de8fd5ca3a1 Mon Sep 17 00:00:00 2001 From: William Cheng Date: Mon, 6 Dec 2021 23:18:48 +0800 Subject: [PATCH 61/61] [C#][functions] minor improvements. (#11034) * better code format * mark generator as beta * update readme * minor code format change * remove docs * add Docs * remove docs * add back docs * mv yaml --- README.md | 3 +- .../other/csharp-netcore-functions.yaml | 6 + docs/generators.md | 2 +- .../CSharpNetCoreReducedClientCodegen.java | 26 +- .../CsharpNetcoreFunctionsServerCodegen.java | 29 +- .../csharp-netcore-functions/.gitignore | 362 ++++++++ .../.openapi-generator-ignore | 23 + .../.openapi-generator/FILES | 51 ++ .../.openapi-generator/VERSION | 1 + .../csharp-netcore-functions/README.md | 159 ++++ .../Tests/Tests/Apis/PetApiTests.cs | 156 ++++ .../Tests/Tests/Apis/StoreApiTests.cs | 103 +++ .../Tests/Tests/Apis/UserApiTests.cs | 148 +++ .../csharp-netcore-functions/appveyor.yml | 9 + .../docs/ApiResponse.md | 13 + .../csharp-netcore-functions/docs/Category.md | 12 + .../csharp-netcore-functions/docs/Order.md | 16 + .../csharp-netcore-functions/docs/Pet.md | 16 + .../csharp-netcore-functions/docs/PetApi.md | 616 +++++++++++++ .../csharp-netcore-functions/docs/StoreApi.md | 298 ++++++ .../csharp-netcore-functions/docs/Tag.md | 12 + .../csharp-netcore-functions/docs/User.md | 18 + .../csharp-netcore-functions/docs/UserApi.md | 603 ++++++++++++ .../generatedSrc/Client/ApiClient.cs | 860 ++++++++++++++++++ .../generatedSrc/Client/ApiException.cs | 68 ++ .../generatedSrc/Client/ApiResponse.cs | 166 ++++ .../generatedSrc/Client/Configuration.cs | 515 +++++++++++ .../generatedSrc/Client/ExceptionFactory.cs | 22 + .../generatedSrc/Client/IApiAccessor.cs | 37 + .../Client/OpenAPIDateConverter.cs | 29 + .../generatedSrc/Functions/PetApi.cs | 104 +++ .../generatedSrc/Functions/StoreApi.cs | 64 ++ .../generatedSrc/Functions/UserApi.cs | 104 +++ .../generatedSrc/Models/ApiResponse.cs | 155 ++++ .../generatedSrc/Models/Category.cs | 146 +++ .../generatedSrc/Models/Order.cs | 223 +++++ .../generatedSrc/Models/Pet.cs | 238 +++++ .../generatedSrc/Models/Tag.cs | 139 +++ .../generatedSrc/Models/User.cs | 234 +++++ .../generatedSrc/README.md | 159 ++++ .../generatedSrc/project.json | 12 + .../csharp-netcore-functions/git_push.sh | 58 ++ .../Models/ApiResponseTests.cs | 86 ++ .../Models/CategoryTests.cs | 78 ++ .../Models/OrderTests.cs | 110 +++ .../Org.OpenAPITools.Test/Models/PetTests.cs | 110 +++ .../Org.OpenAPITools.Test/Models/TagTests.cs | 78 ++ .../Org.OpenAPITools.Test/Models/UserTests.cs | 126 +++ .../src/Org.OpenAPITools/Client/ApiClient.cs | 860 ++++++++++++++++++ .../Org.OpenAPITools/Client/ApiException.cs | 68 ++ .../Org.OpenAPITools/Client/ApiResponse.cs | 166 ++++ .../Org.OpenAPITools/Client/ClientUtils.cs | 229 +++++ .../Org.OpenAPITools/Client/Configuration.cs | 515 +++++++++++ .../Client/ExceptionFactory.cs | 22 + .../Client/GlobalConfiguration.cs | 67 ++ .../src/Org.OpenAPITools/Client/HttpMethod.cs | 33 + .../Org.OpenAPITools/Client/IApiAccessor.cs | 37 + .../Client/IAsynchronousClient.cs | 100 ++ .../Client/IReadableConfiguration.cs | 115 +++ .../Client/ISynchronousClient.cs | 93 ++ .../src/Org.OpenAPITools/Client/Multimap.cs | 295 ++++++ .../Client/OpenAPIDateConverter.cs | 29 + .../Org.OpenAPITools/Client/RequestOptions.cs | 74 ++ .../Client/RetryConfiguration.cs | 21 + .../Models/AbstractOpenAPISchema.cs | 76 ++ 65 files changed, 9385 insertions(+), 18 deletions(-) create mode 100644 bin/configs/other/csharp-netcore-functions.yaml create mode 100644 samples/client/petstore/csharp-netcore-functions/.gitignore create mode 100644 samples/client/petstore/csharp-netcore-functions/.openapi-generator-ignore create mode 100644 samples/client/petstore/csharp-netcore-functions/.openapi-generator/FILES create mode 100644 samples/client/petstore/csharp-netcore-functions/.openapi-generator/VERSION create mode 100644 samples/client/petstore/csharp-netcore-functions/README.md create mode 100644 samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/PetApiTests.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/StoreApiTests.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/UserApiTests.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/appveyor.yml create mode 100644 samples/client/petstore/csharp-netcore-functions/docs/ApiResponse.md create mode 100644 samples/client/petstore/csharp-netcore-functions/docs/Category.md create mode 100644 samples/client/petstore/csharp-netcore-functions/docs/Order.md create mode 100644 samples/client/petstore/csharp-netcore-functions/docs/Pet.md create mode 100644 samples/client/petstore/csharp-netcore-functions/docs/PetApi.md create mode 100644 samples/client/petstore/csharp-netcore-functions/docs/StoreApi.md create mode 100644 samples/client/petstore/csharp-netcore-functions/docs/Tag.md create mode 100644 samples/client/petstore/csharp-netcore-functions/docs/User.md create mode 100644 samples/client/petstore/csharp-netcore-functions/docs/UserApi.md create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiClient.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiException.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiResponse.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/Configuration.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ExceptionFactory.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/IApiAccessor.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/OpenAPIDateConverter.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/PetApi.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/StoreApi.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/UserApi.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/ApiResponse.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Category.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Order.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Pet.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Tag.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/User.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/README.md create mode 100644 samples/client/petstore/csharp-netcore-functions/generatedSrc/project.json create mode 100644 samples/client/petstore/csharp-netcore-functions/git_push.sh create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/ApiResponseTests.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/CategoryTests.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/OrderTests.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/PetTests.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/TagTests.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/UserTests.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiClient.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiException.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiResponse.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ClientUtils.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/Configuration.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ExceptionFactory.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/GlobalConfiguration.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/HttpMethod.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IApiAccessor.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IAsynchronousClient.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IReadableConfiguration.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ISynchronousClient.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/Multimap.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/RequestOptions.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/RetryConfiguration.cs create mode 100644 samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Models/AbstractOpenAPISchema.cs diff --git a/README.md b/README.md index 210de6791d2..804104dd962 100644 --- a/README.md +++ b/README.md @@ -76,7 +76,7 @@ OpenAPI Generator allows generation of API client libraries (SDK generation), se | | Languages/Frameworks | | -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.0, .NET Core 2.0, .NET 5.0. Libraries: RestSharp, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient, Jersey1.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client), **k6**, **Kotlin**, **Lua**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (2.x - 11.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs) | -| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) | +| **Server stubs** | **Ada**, **C#** (ASP.NET Core, NancyFx, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/)), **Kotlin** (Spring Boot, Ktor, Vertx), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** (rust-server), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) | | **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** | | **Configuration files** | [**Apache2**](https://httpd.apache.org/) | | **Others** | **GraphQL**, **JMeter**, **Ktorm**, **MySQL Schema**, **Protocol Buffer**, **WSDL** | @@ -954,6 +954,7 @@ Here is a list of template creators: * C# ASP.NET 5: @jimschubert [:heart:](https://www.patreon.com/jimschubert) * C# ASP.NET Core 3.0: @A-Joshi * C# APS.NET Core 3.1: @phatcher + * C# Azure functions: @Abrhm7786 * C# NancyFX: @mstefaniuk * C++ (Qt5 QHttpEngine): @etherealjoy * C++ Pistache: @sebymiano diff --git a/bin/configs/other/csharp-netcore-functions.yaml b/bin/configs/other/csharp-netcore-functions.yaml new file mode 100644 index 00000000000..6d7e9a691b0 --- /dev/null +++ b/bin/configs/other/csharp-netcore-functions.yaml @@ -0,0 +1,6 @@ +generatorName: csharp-netcore-functions +outputDir: samples/client/petstore/csharp-netcore-functions +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/csharp-netcore-functions +#additionalProperties: +# packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' diff --git a/docs/generators.md b/docs/generators.md index 8d8433cd23f..6ce82ffadbb 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -86,7 +86,7 @@ The following generators are available: * [cpp-qt-qhttpengine-server](generators/cpp-qt-qhttpengine-server.md) * [cpp-restbed-server](generators/cpp-restbed-server.md) * [csharp-nancyfx](generators/csharp-nancyfx.md) -* [csharp-netcore-functions](generators/csharp-netcore-functions.md) +* [csharp-netcore-functions (beta)](generators/csharp-netcore-functions.md) * [erlang-server](generators/erlang-server.md) * [fsharp-functions (beta)](generators/fsharp-functions.md) * [fsharp-giraffe-server (beta)](generators/fsharp-giraffe-server.md) diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java index 8f189b444ba..d0447bd6968 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpNetCoreReducedClientCodegen.java @@ -266,10 +266,10 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { addSwitch(CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES, CodegenConstants.OPTIONAL_EMIT_DEFAULT_VALUES_DESC, this.optionalEmitDefaultValuesFlag); - + addSwitch(CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION, - CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION_DESC, - this.conditionalSerialization); + CodegenConstants.OPTIONAL_CONDITIONAL_SERIALIZATION_DESC, + this.conditionalSerialization); addSwitch(CodegenConstants.OPTIONAL_PROJECT_FILE, CodegenConstants.OPTIONAL_PROJECT_FILE_DESC, @@ -588,7 +588,7 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { additionalProperties.put("multiTarget", true); } else { // just a single value - frameworks = new String [] {inputFramework}; + frameworks = new String[]{inputFramework}; } for (String framework : frameworks) { @@ -600,14 +600,14 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { } if (frameworkStrategy != FrameworkStrategy.NETSTANDARD_2_0 && "restsharp".equals(getLibrary())) { - LOGGER.warn("If using built-in templates, RestSharp only supports netstandard 2.0 or later."); + LOGGER.warn("If using built-in templates, RestSharp only supports netstandard 2.0 or later."); } } if (!strategyMatched) { // throws exception if the input targetFramework is invalid throw new IllegalArgumentException("The input (" + inputFramework + ") contains Invalid .NET framework version: " + - framework + ". List of supported versions: " + + framework + ". List of supported versions: " + frameworkStrategies.stream() .map(p -> p.name) .collect(Collectors.joining(", "))); @@ -634,7 +634,7 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { final AtomicReference excludeTests = new AtomicReference<>(); syncBooleanProperty(additionalProperties, CodegenConstants.EXCLUDE_TESTS, excludeTests::set, false); - syncStringProperty(additionalProperties, "clientPackage", (s) -> { }, clientPackage); + syncStringProperty(additionalProperties, "clientPackage", (s) -> {}, clientPackage); syncStringProperty(additionalProperties, CodegenConstants.API_PACKAGE, this::setApiPackage, apiPackage); syncStringProperty(additionalProperties, CodegenConstants.MODEL_PACKAGE, this::setModelPackage, modelPackage); @@ -669,7 +669,7 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { binRelativePath += "vendor"; additionalProperties.put("binRelativePath", binRelativePath); - if(HTTPCLIENT.equals(getLibrary())) { + if (HTTPCLIENT.equals(getLibrary())) { supportingFiles.add(new SupportingFile("FileParameter.mustache", clientPackageDir, "FileParameter.cs")); typeMapping.put("file", "FileParameter"); } @@ -682,10 +682,10 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { supportingFiles.add(new SupportingFile("ExceptionFactory.mustache", clientPackageDir, "ExceptionFactory.cs")); supportingFiles.add(new SupportingFile("OpenAPIDateConverter.mustache", clientPackageDir, "OpenAPIDateConverter.cs")); supportingFiles.add(new SupportingFile("ClientUtils.mustache", clientPackageDir, "ClientUtils.cs")); - if(needsCustomHttpMethod) { + if (needsCustomHttpMethod) { supportingFiles.add(new SupportingFile("HttpMethod.mustache", clientPackageDir, "HttpMethod.cs")); } - if(needsUriBuilder) { + if (needsUriBuilder) { supportingFiles.add(new SupportingFile("WebRequestPathBuilder.mustache", clientPackageDir, "WebRequestPathBuilder.cs")); } if (ProcessUtils.hasHttpSignatureMethods(openAPI)) { @@ -736,7 +736,7 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { this.optionalEmitDefaultValuesFlag = flag; } - public void setConditionalSerialization(boolean flag){ + public void setConditionalSerialization(boolean flag) { this.conditionalSerialization = flag; } @@ -771,8 +771,8 @@ public class CSharpNetCoreReducedClientCodegen extends AbstractCSharpCodegen { throw new IllegalArgumentException("Invalid .NET framework version: " + dotnetFramework + ". List of supported versions: " + frameworkStrategies.stream() - .map(p -> p.name) - .collect(Collectors.joining(", "))); + .map(p -> p.name) + .collect(Collectors.joining(", "))); } else { this.targetFramework = dotnetFramework; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java index f2ab9939c34..8e020f3e641 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CsharpNetcoreFunctionsServerCodegen.java @@ -1,3 +1,19 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * 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. + */ + package org.openapitools.codegen.languages; import org.openapitools.codegen.*; @@ -11,10 +27,12 @@ import java.util.*; import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedClientCodegen { +public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedClientCodegen { public static final String PROJECT_NAME = "projectName"; final Logger LOGGER = LoggerFactory.getLogger(CsharpNetcoreFunctionsServerCodegen.class); @@ -33,6 +51,11 @@ public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedCli public CsharpNetcoreFunctionsServerCodegen() { super(); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + outputFolder = "generated-code" + File.separator + "csharp"; modelTemplateFiles.put("model.mustache", ".cs"); apiTemplateFiles.put("functions.mustache", ".cs"); @@ -42,7 +65,7 @@ public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedCli String clientPackageDir = "generatedSrc/Client"; supportingFiles.add(new SupportingFile("README.mustache", "generatedSrc", "README.md")); supportingFiles.add(new SupportingFile("project.mustache", "generatedSrc", "project.json")); - + supportingFiles.add(new SupportingFile("IApiAccessor.mustache", clientPackageDir, "IApiAccessor.cs")); supportingFiles.add(new SupportingFile("Configuration.mustache", @@ -66,7 +89,7 @@ public class CsharpNetcoreFunctionsServerCodegen extends CSharpNetCoreReducedCli @Override public String modelFileFolder() { - return outputFolder + File.separator + "generatedSrc" + File.separator + "Models"; + return outputFolder + File.separator + "generatedSrc" + File.separator + "Models"; } @Override diff --git a/samples/client/petstore/csharp-netcore-functions/.gitignore b/samples/client/petstore/csharp-netcore-functions/.gitignore new file mode 100644 index 00000000000..1ee53850b84 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/samples/client/petstore/csharp-netcore-functions/.openapi-generator-ignore b/samples/client/petstore/csharp-netcore-functions/.openapi-generator-ignore new file mode 100644 index 00000000000..7484ee590a3 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp-netcore-functions/.openapi-generator/FILES b/samples/client/petstore/csharp-netcore-functions/.openapi-generator/FILES new file mode 100644 index 00000000000..e6e8df0a401 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/.openapi-generator/FILES @@ -0,0 +1,51 @@ +.gitignore +Docs/PetApi.md +Docs/StoreApi.md +Docs/UserApi.md +README.md +appveyor.yml +docs/ApiResponse.md +docs/Category.md +docs/Order.md +docs/Pet.md +docs/Tag.md +docs/User.md +generatedSrc/Client/ApiClient.cs +generatedSrc/Client/ApiException.cs +generatedSrc/Client/ApiResponse.cs +generatedSrc/Client/Configuration.cs +generatedSrc/Client/ExceptionFactory.cs +generatedSrc/Client/IApiAccessor.cs +generatedSrc/Client/OpenAPIDateConverter.cs +generatedSrc/Functions/PetApi.cs +generatedSrc/Functions/PetApi.cs +generatedSrc/Functions/StoreApi.cs +generatedSrc/Functions/StoreApi.cs +generatedSrc/Functions/UserApi.cs +generatedSrc/Functions/UserApi.cs +generatedSrc/Models/ApiResponse.cs +generatedSrc/Models/Category.cs +generatedSrc/Models/Order.cs +generatedSrc/Models/Pet.cs +generatedSrc/Models/Tag.cs +generatedSrc/Models/User.cs +generatedSrc/README.md +generatedSrc/project.json +git_push.sh +src/Org.OpenAPITools/Client/ApiClient.cs +src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/Configuration.cs +src/Org.OpenAPITools/Client/ExceptionFactory.cs +src/Org.OpenAPITools/Client/GlobalConfiguration.cs +src/Org.OpenAPITools/Client/HttpMethod.cs +src/Org.OpenAPITools/Client/IApiAccessor.cs +src/Org.OpenAPITools/Client/IAsynchronousClient.cs +src/Org.OpenAPITools/Client/IReadableConfiguration.cs +src/Org.OpenAPITools/Client/ISynchronousClient.cs +src/Org.OpenAPITools/Client/Multimap.cs +src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs +src/Org.OpenAPITools/Client/RequestOptions.cs +src/Org.OpenAPITools/Client/RetryConfiguration.cs +src/Org.OpenAPITools/Models/AbstractOpenAPISchema.cs diff --git a/samples/client/petstore/csharp-netcore-functions/.openapi-generator/VERSION b/samples/client/petstore/csharp-netcore-functions/.openapi-generator/VERSION new file mode 100644 index 00000000000..4077803655c --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/.openapi-generator/VERSION @@ -0,0 +1 @@ +5.3.1-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore-functions/README.md b/samples/client/petstore/csharp-netcore-functions/README.md new file mode 100644 index 00000000000..a531ad1e602 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/README.md @@ -0,0 +1,159 @@ +# Org.OpenAPITools - the C# library for the OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CsharpNetcoreFunctionsServerCodegen + + +## Frameworks supported +- .NET Core >=1.0 +- .NET Framework >=4.6 +- Mono/Xamarin >=vNext + + +## Dependencies + +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.11.7 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 12.0.3 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later + +The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: +``` +Install-Package RestSharp +Install-Package Newtonsoft.Json +Install-Package JsonSubTypes +Install-Package System.ComponentModel.Annotations +``` + +NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742). +NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406). + + +## Installation +Generate the DLL using your preferred tool (e.g. `dotnet build`) + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; +``` + +## Usage + +To use the API client with a HTTP proxy, setup a `System.Net.WebProxy` +```csharp +Configuration c = new Configuration(); +System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/"); +webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials; +c.Proxy = webProxy; +``` + + +## Getting Started + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class Example + { + public static void Main() + { + + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Add a new pet to the store + Pet result = apiInstance.AddPet(pet); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [Models.ApiResponse](docs/ApiResponse.md) + - [Models.Category](docs/Category.md) + - [Models.Order](docs/Order.md) + - [Models.Pet](docs/Pet.md) + - [Models.Tag](docs/Tag.md) + - [Models.User](docs/User.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/PetApiTests.cs b/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/PetApiTests.cs new file mode 100644 index 00000000000..9ee31e31c3d --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/PetApiTests.cs @@ -0,0 +1,156 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using Xunit; + +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Apis; +// uncomment below to import models +//using Org.OpenAPITools.Models; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing PetApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class PetApiTests : IDisposable + { + private PetApi instance; + + public PetApiTests() + { + instance = new PetApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of PetApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' PetApi + //Assert.IsType(instance); + } + + /// + /// Test AddPet + /// + [Fact] + public void AddPetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Pet pet = null; + //var response = instance.AddPet(pet); + //Assert.IsType(response); + } + + /// + /// Test DeletePet + /// + [Fact] + public void DeletePetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //string apiKey = null; + //instance.DeletePet(petId, apiKey); + } + + /// + /// Test FindPetsByStatus + /// + [Fact] + public void FindPetsByStatusTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List status = null; + //var response = instance.FindPetsByStatus(status); + //Assert.IsType>(response); + } + + /// + /// Test FindPetsByTags + /// + [Fact] + public void FindPetsByTagsTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List tags = null; + //var response = instance.FindPetsByTags(tags); + //Assert.IsType>(response); + } + + /// + /// Test GetPetById + /// + [Fact] + public void GetPetByIdTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //var response = instance.GetPetById(petId); + //Assert.IsType(response); + } + + /// + /// Test UpdatePet + /// + [Fact] + public void UpdatePetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Pet pet = null; + //var response = instance.UpdatePet(pet); + //Assert.IsType(response); + } + + /// + /// Test UpdatePetWithForm + /// + [Fact] + public void UpdatePetWithFormTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //string name = null; + //string status = null; + //instance.UpdatePetWithForm(petId, name, status); + } + + /// + /// Test UploadFile + /// + [Fact] + public void UploadFileTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long petId = null; + //string additionalMetadata = null; + //System.IO.Stream file = null; + //var response = instance.UploadFile(petId, additionalMetadata, file); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/StoreApiTests.cs b/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/StoreApiTests.cs new file mode 100644 index 00000000000..59206b2a763 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/StoreApiTests.cs @@ -0,0 +1,103 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using Xunit; + +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Apis; +// uncomment below to import models +//using Org.OpenAPITools.Models; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing StoreApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class StoreApiTests : IDisposable + { + private StoreApi instance; + + public StoreApiTests() + { + instance = new StoreApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of StoreApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' StoreApi + //Assert.IsType(instance); + } + + /// + /// Test DeleteOrder + /// + [Fact] + public void DeleteOrderTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string orderId = null; + //instance.DeleteOrder(orderId); + } + + /// + /// Test GetInventory + /// + [Fact] + public void GetInventoryTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.GetInventory(); + //Assert.IsType>(response); + } + + /// + /// Test GetOrderById + /// + [Fact] + public void GetOrderByIdTest() + { + // TODO uncomment below to test the method and replace null with proper value + //long orderId = null; + //var response = instance.GetOrderById(orderId); + //Assert.IsType(response); + } + + /// + /// Test PlaceOrder + /// + [Fact] + public void PlaceOrderTest() + { + // TODO uncomment below to test the method and replace null with proper value + //Order order = null; + //var response = instance.PlaceOrder(order); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/UserApiTests.cs b/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/UserApiTests.cs new file mode 100644 index 00000000000..031e222ca0b --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/Tests/Tests/Apis/UserApiTests.cs @@ -0,0 +1,148 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using Xunit; + +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Apis; +// uncomment below to import models +//using Org.OpenAPITools.Models; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing UserApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class UserApiTests : IDisposable + { + private UserApi instance; + + public UserApiTests() + { + instance = new UserApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of UserApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' UserApi + //Assert.IsType(instance); + } + + /// + /// Test CreateUser + /// + [Fact] + public void CreateUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //User user = null; + //instance.CreateUser(user); + } + + /// + /// Test CreateUsersWithArrayInput + /// + [Fact] + public void CreateUsersWithArrayInputTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List user = null; + //instance.CreateUsersWithArrayInput(user); + } + + /// + /// Test CreateUsersWithListInput + /// + [Fact] + public void CreateUsersWithListInputTest() + { + // TODO uncomment below to test the method and replace null with proper value + //List user = null; + //instance.CreateUsersWithListInput(user); + } + + /// + /// Test DeleteUser + /// + [Fact] + public void DeleteUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //instance.DeleteUser(username); + } + + /// + /// Test GetUserByName + /// + [Fact] + public void GetUserByNameTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //var response = instance.GetUserByName(username); + //Assert.IsType(response); + } + + /// + /// Test LoginUser + /// + [Fact] + public void LoginUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //string password = null; + //var response = instance.LoginUser(username, password); + //Assert.IsType(response); + } + + /// + /// Test LogoutUser + /// + [Fact] + public void LogoutUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //instance.LogoutUser(); + } + + /// + /// Test UpdateUser + /// + [Fact] + public void UpdateUserTest() + { + // TODO uncomment below to test the method and replace null with proper value + //string username = null; + //User user = null; + //instance.UpdateUser(username, user); + } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/appveyor.yml b/samples/client/petstore/csharp-netcore-functions/appveyor.yml new file mode 100644 index 00000000000..f76f63cee50 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/appveyor.yml @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\Org.OpenAPITools\Org.OpenAPITools.csproj -o ../../output -c Release --no-build diff --git a/samples/client/petstore/csharp-netcore-functions/docs/ApiResponse.md b/samples/client/petstore/csharp-netcore-functions/docs/ApiResponse.md new file mode 100644 index 00000000000..2bcb247bbd9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/docs/ApiResponse.md @@ -0,0 +1,13 @@ +# Org.OpenAPITools.Models.ApiResponse +Describes the result of uploading an image resource + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Code** | **int** | | [optional] +**Type** | **string** | | [optional] +**Message** | **string** | | [optional] + +[[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-functions/docs/Category.md b/samples/client/petstore/csharp-netcore-functions/docs/Category.md new file mode 100644 index 00000000000..ff6c3ede4bb --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/docs/Category.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Models.Category +A category for a pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Name** | **string** | | [optional] + +[[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-functions/docs/Order.md b/samples/client/petstore/csharp-netcore-functions/docs/Order.md new file mode 100644 index 00000000000..2f13a5b7d66 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/docs/Order.md @@ -0,0 +1,16 @@ +# Org.OpenAPITools.Models.Order +An order for a pets from the pet store + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**PetId** | **long** | | [optional] +**Quantity** | **int** | | [optional] +**ShipDate** | **DateTime** | | [optional] +**Status** | **string** | Order Status | [optional] +**Complete** | **bool** | | [optional] [default to false] + +[[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-functions/docs/Pet.md b/samples/client/petstore/csharp-netcore-functions/docs/Pet.md new file mode 100644 index 00000000000..bb37eb83fdb --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/docs/Pet.md @@ -0,0 +1,16 @@ +# Org.OpenAPITools.Models.Pet +A pet for sale in the pet store + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Category** | [**Category**](Category.md) | | [optional] +**Name** | **string** | | +**PhotoUrls** | **List<string>** | | +**Tags** | [**List<Tag>**](Tag.md) | | [optional] +**Status** | **string** | pet status in the store | [optional] + +[[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-functions/docs/PetApi.md b/samples/client/petstore/csharp-netcore-functions/docs/PetApi.md new file mode 100644 index 00000000000..5251662068a --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/docs/PetApi.md @@ -0,0 +1,616 @@ +# Org.OpenAPITools.Apis.PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AddPet**](PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +[**DeletePet**](PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +[**FindPetsByStatus**](PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +[**FindPetsByTags**](PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +[**GetPetById**](PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +[**UpdatePet**](PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +[**UpdatePetWithForm**](PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**UploadFile**](PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **AddPet** +> Pet AddPet (Pet pet) + +Add a new pet to the store + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class AddPetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Add a new pet to the store + Pet result = apiInstance.AddPet(pet); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + +[[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) + + +# **DeletePet** +> void DeletePet (long petId, string apiKey = null) + +Deletes a pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class DeletePetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789; // long | Pet id to delete + var apiKey = apiKey_example; // string | (optional) + + try + { + // Deletes a pet + apiInstance.DeletePet(petId, apiKey); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.DeletePet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long**| Pet id to delete | + **apiKey** | **string**| | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid pet value | - | + +[[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) + + +# **FindPetsByStatus** +> List<Pet> FindPetsByStatus (List status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class FindPetsByStatusExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var status = new List(); // List | Status values that need to be considered for filter + + try + { + // Finds Pets by status + List result = apiInstance.FindPetsByStatus(status); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.FindPetsByStatus: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**List<string>**](string.md)| Status values that need to be considered for filter | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + +[[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) + + +# **FindPetsByTags** +> List<Pet> FindPetsByTags (List tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class FindPetsByTagsExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var tags = new List(); // List | Tags to filter by + + try + { + // Finds Pets by tags + List result = apiInstance.FindPetsByTags(tags); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.FindPetsByTags: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**List<string>**](string.md)| Tags to filter by | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + +[[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) + + +# **GetPetById** +> Pet GetPetById (long petId) + +Find pet by ID + +Returns a single pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class GetPetByIdExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new PetApi(config); + var petId = 789; // long | ID of pet to return + + try + { + // Find pet by ID + Pet result = apiInstance.GetPetById(petId); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.GetPetById: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + +[[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) + + +# **UpdatePet** +> Pet UpdatePet (Pet pet) + +Update an existing pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class UpdatePetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Update an existing pet + Pet result = apiInstance.UpdatePet(pet); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UpdatePet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + +[[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) + + +# **UpdatePetWithForm** +> void UpdatePetWithForm (long petId, string name = null, string status = null) + +Updates a pet in the store with form data + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class UpdatePetWithFormExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789; // long | ID of pet that needs to be updated + var name = name_example; // string | Updated name of the pet (optional) + var status = status_example; // string | Updated status of the pet (optional) + + try + { + // Updates a pet in the store with form data + apiInstance.UpdatePetWithForm(petId, name, status); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UpdatePetWithForm: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long**| ID of pet that needs to be updated | + **name** | **string**| Updated name of the pet | [optional] + **status** | **string**| Updated status of the pet | [optional] + +### Return type + +void (empty response body) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + +[[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) + + +# **UploadFile** +> ApiResponse UploadFile (long petId, string additionalMetadata = null, System.IO.Stream file = null) + +uploads an image + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class UploadFileExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var petId = 789; // long | ID of pet to update + var additionalMetadata = additionalMetadata_example; // string | Additional data to pass to server (optional) + var file = BINARY_DATA_HERE; // System.IO.Stream | file to upload (optional) + + try + { + // uploads an image + ApiResponse result = apiInstance.UploadFile(petId, additionalMetadata, file); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.UploadFile: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **long**| ID of pet to update | + **additionalMetadata** | **string**| Additional data to pass to server | [optional] + **file** | **System.IO.Stream****System.IO.Stream**| file to upload | [optional] + +### Return type + +[**ApiResponse**](ApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[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/client/petstore/csharp-netcore-functions/docs/StoreApi.md b/samples/client/petstore/csharp-netcore-functions/docs/StoreApi.md new file mode 100644 index 00000000000..a1ad605d05e --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/docs/StoreApi.md @@ -0,0 +1,298 @@ +# Org.OpenAPITools.Apis.StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**DeleteOrder**](StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**GetInventory**](StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +[**GetOrderById**](StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +[**PlaceOrder**](StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet + + + +# **DeleteOrder** +> void DeleteOrder (string orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class DeleteOrderExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + var apiInstance = new StoreApi(config); + var orderId = orderId_example; // string | ID of the order that needs to be deleted + + try + { + // Delete purchase order by ID + apiInstance.DeleteOrder(orderId); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.DeleteOrder: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **string**| ID of the order that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +[[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) + + +# **GetInventory** +> Dictionary<string, int> GetInventory () + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class GetInventoryExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new StoreApi(config); + + try + { + // Returns pet inventories by status + Dictionary result = apiInstance.GetInventory(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.GetInventory: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**Dictionary** + +### 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 | - | + +[[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) + + +# **GetOrderById** +> Order GetOrderById (long orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class GetOrderByIdExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + var apiInstance = new StoreApi(config); + var orderId = 789; // long | ID of pet that needs to be fetched + + try + { + // Find purchase order by ID + Order result = apiInstance.GetOrderById(orderId); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.GetOrderById: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + +[[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) + + +# **PlaceOrder** +> Order PlaceOrder (Order order) + +Place an order for a pet + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class PlaceOrderExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + var apiInstance = new StoreApi(config); + var order = new Order(); // Order | order placed for purchasing the pet + + try + { + // Place an order for a pet + Order result = apiInstance.PlaceOrder(order); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling StoreApi.PlaceOrder: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + +[[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/client/petstore/csharp-netcore-functions/docs/Tag.md b/samples/client/petstore/csharp-netcore-functions/docs/Tag.md new file mode 100644 index 00000000000..97b08989ea6 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/docs/Tag.md @@ -0,0 +1,12 @@ +# Org.OpenAPITools.Models.Tag +A tag for a pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Name** | **string** | | [optional] + +[[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-functions/docs/User.md b/samples/client/petstore/csharp-netcore-functions/docs/User.md new file mode 100644 index 00000000000..d665fa56193 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/docs/User.md @@ -0,0 +1,18 @@ +# Org.OpenAPITools.Models.User +A User who is purchasing from the pet store + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **long** | | [optional] +**Username** | **string** | | [optional] +**FirstName** | **string** | | [optional] +**LastName** | **string** | | [optional] +**Email** | **string** | | [optional] +**Password** | **string** | | [optional] +**Phone** | **string** | | [optional] +**UserStatus** | **int** | User Status | [optional] + +[[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-functions/docs/UserApi.md b/samples/client/petstore/csharp-netcore-functions/docs/UserApi.md new file mode 100644 index 00000000000..858ec4e2be1 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/docs/UserApi.md @@ -0,0 +1,603 @@ +# Org.OpenAPITools.Apis.UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**CreateUser**](UserApi.md#createuser) | **POST** /user | Create user +[**CreateUsersWithArrayInput**](UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +[**CreateUsersWithListInput**](UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +[**DeleteUser**](UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +[**GetUserByName**](UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +[**LoginUser**](UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +[**LogoutUser**](UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +[**UpdateUser**](UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +# **CreateUser** +> void CreateUser (User user) + +Create user + +This can only be done by the logged in user. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class CreateUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new UserApi(config); + var user = new User(); // User | Created user object + + try + { + // Create user + apiInstance.CreateUser(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[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) + + +# **CreateUsersWithArrayInput** +> void CreateUsersWithArrayInput (List user) + +Creates list of users with given input array + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class CreateUsersWithArrayInputExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new UserApi(config); + var user = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithArrayInput(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithArrayInput: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**List<User>**](User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[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) + + +# **CreateUsersWithListInput** +> void CreateUsersWithListInput (List user) + +Creates list of users with given input array + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class CreateUsersWithListInputExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new UserApi(config); + var user = new List(); // List | List of user object + + try + { + // Creates list of users with given input array + apiInstance.CreateUsersWithListInput(user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.CreateUsersWithListInput: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**List<User>**](User.md)| List of user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[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) + + +# **DeleteUser** +> void DeleteUser (string username) + +Delete user + +This can only be done by the logged in user. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class DeleteUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new UserApi(config); + var username = username_example; // string | The name that needs to be deleted + + try + { + // Delete user + apiInstance.DeleteUser(username); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.DeleteUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be deleted | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +[[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) + + +# **GetUserByName** +> User GetUserByName (string username) + +Get user by user name + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class GetUserByNameExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + var apiInstance = new UserApi(config); + var username = username_example; // string | The name that needs to be fetched. Use user1 for testing. + + try + { + // Get user by user name + User result = apiInstance.GetUserByName(username); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.GetUserByName: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + +[[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) + + +# **LoginUser** +> string LoginUser (string username, string password) + +Logs user into the system + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class LoginUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + var apiInstance = new UserApi(config); + var username = username_example; // string | The user name for login + var password = password_example; // string | The password for login in clear text + + try + { + // Logs user into the system + string result = apiInstance.LoginUser(username, password); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.LoginUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| The user name for login | + **password** | **string**| The password for login in clear text | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
    * X-Rate-Limit - calls per hour allowed by the user
    * X-Expires-After - date in UTC when token expires
    | +| **400** | Invalid username/password supplied | - | + +[[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) + + +# **LogoutUser** +> void LogoutUser () + +Logs out current logged in user session + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class LogoutUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new UserApi(config); + + try + { + // Logs out current logged in user session + apiInstance.LogoutUser(); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.LogoutUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + +[[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) + + +# **UpdateUser** +> void UpdateUser (string username, User user) + +Updated user + +This can only be done by the logged in user. + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class UpdateUserExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure API key authorization: api_key + config.AddApiKey("api_key", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key", "Bearer"); + + var apiInstance = new UserApi(config); + var username = username_example; // string | name that need to be deleted + var user = new User(); // User | Updated user object + + try + { + // Updated user + apiInstance.UpdateUser(username, user); + } + catch (ApiException e) + { + Debug.Print("Exception when calling UserApi.UpdateUser: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **string**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### Return type + +void (empty response body) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + +[[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/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiClient.cs new file mode 100644 index 00000000000..4f68a59871e --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiClient.cs @@ -0,0 +1,860 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +using RestSharp; +using RestSharp.Deserializers; +using RestSharpMethod = RestSharp.Method; +using Polly; + +namespace Org.OpenAPITools.Client +{ + /// + /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is Org.OpenAPITools.Models.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return ((Org.OpenAPITools.Models.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public T Deserialize(IRestResponse response) + { + var result = (T)Deserialize(response, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal object Deserialize(IRestResponse response, Type type) + { + if (type == typeof(byte[])) // return byte array + { + return response.RawBytes; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = response.RawBytes; + if (response.Headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in response.Headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(response.Content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), + /// encapsulating general REST accessor use cases. + /// + public partial class ApiClient : ISynchronousClient, IAsynchronousClient + { + private readonly string _baseUrl; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accomodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse response); + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + public ApiClient() + { + _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + } + + /// + /// Initializes a new instance of the + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + _baseUrl = basePath; + } + + /// + /// Constructs the RestSharp version of an http method + /// + /// Swagger Client Custom HttpMethod + /// RestSharp's HttpMethod instance. + /// + private RestSharpMethod Method(HttpMethod method) + { + RestSharpMethod other; + switch (method) + { + case HttpMethod.Get: + other = RestSharpMethod.GET; + break; + case HttpMethod.Post: + other = RestSharpMethod.POST; + break; + case HttpMethod.Put: + other = RestSharpMethod.PUT; + break; + case HttpMethod.Delete: + other = RestSharpMethod.DELETE; + break; + case HttpMethod.Head: + other = RestSharpMethod.HEAD; + break; + case HttpMethod.Options: + other = RestSharpMethod.OPTIONS; + break; + case HttpMethod.Patch: + other = RestSharpMethod.PATCH; + break; + default: + throw new ArgumentOutOfRangeException("method", method, null); + } + + return other; + } + + /// + /// Provides all logic for constructing a new RestSharp . + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the RestSharp request. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new RestRequest instance. + /// + private RestRequest NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + RestRequest request = new RestRequest(Method(method)) + { + Resource = path, + JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) + }; + + if (options.PathParameters != null) + { + foreach (var pathParam in options.PathParameters) + { + request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); + } + } + + if (options.QueryParameters != null) + { + foreach (var queryParam in options.QueryParameters) + { + foreach (var value in queryParam.Value) + { + request.AddQueryParameter(queryParam.Key, value); + } + } + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.AddHeader(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + request.AddHeader(headerParam.Key, value); + } + } + } + + if (options.FormParameters != null) + { + foreach (var formParam in options.FormParameters) + { + request.AddParameter(formParam.Key, formParam.Value); + } + } + + if (options.Data != null) + { + if (options.Data is Stream stream) + { + var contentType = "application/octet-stream"; + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes[0]; + } + + var bytes = ClientUtils.ReadAsBytes(stream); + request.AddParameter(contentType, bytes, ParameterType.RequestBody); + } + else + { + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) + { + request.RequestFormat = DataFormat.Json; + } + else + { + // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. + } + } + else + { + // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. + request.RequestFormat = DataFormat.Json; + } + + request.AddJsonBody(options.Data); + } + } + + if (options.FileParameters != null) + { + foreach (var fileParam in options.FileParameters) + { + var bytes = ClientUtils.ReadAsBytes(fileParam.Value); + var fileStream = fileParam.Value as FileStream; + if (fileStream != null) + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + else + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + } + } + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + request.AddCookie(cookie.Name, cookie.Value); + } + } + + return request; + } + + private ApiResponse ToApiResponse(IRestResponse response) + { + T result = response.Data; + string rawContent = response.Content; + + var transformed = new ApiResponse(response.StatusCode, new Multimap(), result, rawContent) + { + ErrorText = response.ErrorMessage, + Cookies = new List() + }; + + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.Cookies != null) + { + foreach (var responseCookies in response.Cookies) + { + transformed.Cookies.Add( + new Cookie( + responseCookies.Name, + responseCookies.Value, + responseCookies.Path, + responseCookies.Domain) + ); + } + } + + return transformed; + } + + private ApiResponse Exec(RestRequest req, IReadableConfiguration configuration) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = client.Execute(req); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + private async Task> ExecAsync(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(req, cancellationToken).ConfigureAwait(false); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken); + } + #endregion IAsynchronousClient + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Patch, path, options, config), config); + } + #endregion ISynchronousClient + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiException.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiException.cs new file mode 100644 index 00000000000..dcc378ad208 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiException.cs @@ -0,0 +1,68 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public object ErrorContent { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() { } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + /// HTTP Headers. + public ApiException(int errorCode, string message, object errorContent = null, Multimap headers = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + this.Headers = headers; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiResponse.cs new file mode 100644 index 00000000000..6d91a6f7a47 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ApiResponse.cs @@ -0,0 +1,166 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// The content of this response + /// + Object Content { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + Multimap Headers { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + List Cookies { get; set; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + } + + /// + /// API Response + /// + public class ApiResponse : IApiResponse + { + #region Properties + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + public string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + public List Cookies { get; set; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The data type of + /// + public object Content + { + get { return Data; } + } + + /// + /// The raw content + /// + public string RawContent { get; } + + #endregion Properties + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data, string rawContent) + { + StatusCode = statusCode; + Headers = headers; + Data = data; + RawContent = rawContent; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data) : this(statusCode, headers, data, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null) + { + } + + #endregion Constructors + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/Configuration.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/Configuration.cs new file mode 100644 index 00000000000..896bd754ea5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/Configuration.cs @@ -0,0 +1,515 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "1.0.0"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var status = (int)response.StatusCode; + if (status >= 400) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.RawContent), + response.RawContent, response.Headers); + } + return null; + }; + + #endregion Static Members + + #region Private Members + + /// + /// Defines the base path of the target API server. + /// Example: http://localhost:3000/v1/ + /// + private string _basePath; + + /// + /// Gets or sets the API key based on the authentication name. + /// This is the key and value comprising the "secret" for acessing an API. + /// + /// The API key. + private IDictionary _apiKey; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + + /// + /// Gets or sets the servers defined in the OpenAPI spec. + /// + /// The servers + private IList> _servers; + #endregion Private Members + + #region Constructors + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration() + { + Proxy = null; + UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + BasePath = "http://petstore.swagger.io/v2"; + DefaultHeaders = new ConcurrentDictionary(); + ApiKey = new ConcurrentDictionary(); + ApiKeyPrefix = new ConcurrentDictionary(); + Servers = new List>() + { + { + new Dictionary { + {"url", "http://petstore.swagger.io/v2"}, + {"description", "No description provided"}, + } + } + }; + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration( + IDictionary defaultHeaders, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "http://petstore.swagger.io/v2") : this() + { + if (string.IsNullOrWhiteSpace(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeaders == null) + throw new ArgumentNullException("defaultHeaders"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeaders) + { + DefaultHeaders.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + #endregion Constructors + + #region Properties + + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath { + get { return _basePath; } + set { _basePath = value; } + } + + /// + /// Gets or sets the default header. + /// + [Obsolete("Use DefaultHeaders instead.")] + public virtual IDictionary DefaultHeader + { + get + { + return DefaultHeaders; + } + set + { + DefaultHeaders = value; + } + } + + /// + /// Gets or sets the default headers. + /// + public virtual IDictionary DefaultHeaders { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout { get; set; } + + /// + /// Gets or sets the proxy + /// + /// Proxy. + public virtual WebProxy Proxy { get; set; } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + string apiKeyValue; + ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); + string apiKeyPrefix; + if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) + { + return apiKeyPrefix + " " + apiKeyValue; + } + + return apiKeyValue; + } + + /// + /// Gets or sets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + public X509CertificateCollection ClientCertificates { get; set; } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// This helper property simplifies code generation. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + _tempFolderPath = Path.GetTempPath(); + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + { + _tempFolderPath = value; + } + else + { + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + } + + /// + /// Gets or sets the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// Whatever you set here will be prepended to the value defined in AddApiKey. + /// + /// An example invocation here might be: + /// + /// ApiKeyPrefix["Authorization"] = "Bearer"; + /// + /// … where ApiKey["Authorization"] would then be used to set the value of your bearer token. + /// + /// + /// OAuth2 workflows should set tokens via AccessToken. + /// + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + + /// + /// Gets or sets the servers. + /// + /// The servers. + public virtual IList> Servers + { + get { return _servers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Servers may not be null."); + } + _servers = value; + } + } + + /// + /// Returns URL based on server settings without providing values + /// for the variables + /// + /// Array index of the server settings. + /// The server URL. + public string GetServerUrl(int index) + { + return GetServerUrl(index, null); + } + + /// + /// Returns URL based on server settings. + /// + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + public string GetServerUrl(int index, Dictionary inputVariables) + { + if (index < 0 || index >= Servers.Count) + { + throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {Servers.Count}."); + } + + if (inputVariables == null) + { + inputVariables = new Dictionary(); + } + + IReadOnlyDictionary server = Servers[index]; + string url = (string)server["url"]; + + // go through variable and assign a value + foreach (KeyValuePair variable in (IReadOnlyDictionary)server["variables"]) + { + + IReadOnlyDictionary serverVariables = (IReadOnlyDictionary)(variable.Value); + + if (inputVariables.ContainsKey(variable.Key)) + { + if (((List)serverVariables["enum_values"]).Contains(inputVariables[variable.Key])) + { + url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]); + } + else + { + throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List)serverVariables["enum_values"]}"); + } + } + else + { + // use defualt value + url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]); + } + } + + return url; + } + + #endregion Properties + + #region Methods + + /// + /// Returns a string with essential information for debugging. + /// + public static string ToDebugReport() + { + string report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: 1.0.0\n"; + report += " SDK Package Version: 1.0.0\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + + #region Static Members + /// + /// Merge configurations. + /// + /// First configuration. + /// Second configuration. + /// Merged configuration. + public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second) + { + if (second == null) return first ?? GlobalConfiguration.Instance; + + Dictionary apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value; + foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value; + foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value; + + var config = new Configuration + { + ApiKey = apiKey, + ApiKeyPrefix = apiKeyPrefix, + DefaultHeaders = defaultHeaders, + BasePath = second.BasePath ?? first.BasePath, + Timeout = second.Timeout, + Proxy = second.Proxy ?? first.Proxy, + UserAgent = second.UserAgent ?? first.UserAgent, + Username = second.Username ?? first.Username, + Password = second.Password ?? first.Password, + AccessToken = second.AccessToken ?? first.AccessToken, + TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, + DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat + }; + return config; + } + #endregion Static Members + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ExceptionFactory.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ExceptionFactory.cs new file mode 100644 index 00000000000..6ae2a10aae4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/ExceptionFactory.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IApiResponse response); +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/IApiAccessor.cs new file mode 100644 index 00000000000..c8a78e995ce --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/IApiAccessor.cs @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + IReadableConfiguration Configuration { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + string GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/OpenAPIDateConverter.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/OpenAPIDateConverter.cs new file mode 100644 index 00000000000..dcc79edd944 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Client/OpenAPIDateConverter.cs @@ -0,0 +1,29 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using Newtonsoft.Json.Converters; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/PetApi.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/PetApi.cs new file mode 100644 index 00000000000..5bed004e613 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/PetApi.cs @@ -0,0 +1,104 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Net; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Extensions.Http; + +namespace Org.OpenAPITools.Apis +{ + public partial class PetApi + { + [FunctionName("PetApi_AddPet")] + public async Task _AddPet([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/pet")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("AddPet"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("PetApi_DeletePet")] + public async Task _DeletePet([HttpTrigger(AuthorizationLevel.Anonymous, "DELETE", Route = "/pet/{petId}")]HttpRequest req, ExecutionContext context, long petId) + { + var method = this.GetType().GetMethod("DeletePet"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("PetApi_FindPetsByStatus")] + public async Task _FindPetsByStatus([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/pet/findByStatus")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("FindPetsByStatus"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("PetApi_FindPetsByTags")] + public async Task _FindPetsByTags([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/pet/findByTags")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("FindPetsByTags"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("PetApi_GetPetById")] + public async Task _GetPetById([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/pet/{petId}")]HttpRequest req, ExecutionContext context, long petId) + { + var method = this.GetType().GetMethod("GetPetById"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("PetApi_UpdatePet")] + public async Task _UpdatePet([HttpTrigger(AuthorizationLevel.Anonymous, "PUT", Route = "/pet")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("UpdatePet"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("PetApi_UpdatePetWithForm")] + public async Task _UpdatePetWithForm([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/pet/{petId}")]HttpRequest req, ExecutionContext context, long petId) + { + var method = this.GetType().GetMethod("UpdatePetWithForm"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("PetApi_UploadFile")] + public async Task _UploadFile([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/pet/{petId}/uploadImage")]HttpRequest req, ExecutionContext context, long petId) + { + var method = this.GetType().GetMethod("UploadFile"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + } +} + diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/StoreApi.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/StoreApi.cs new file mode 100644 index 00000000000..a41afaa34ab --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/StoreApi.cs @@ -0,0 +1,64 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Net; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Extensions.Http; + +namespace Org.OpenAPITools.Apis +{ + public partial class StoreApi + { + [FunctionName("StoreApi_DeleteOrder")] + public async Task _DeleteOrder([HttpTrigger(AuthorizationLevel.Anonymous, "DELETE", Route = "/store/order/{orderId}")]HttpRequest req, ExecutionContext context, string orderId) + { + var method = this.GetType().GetMethod("DeleteOrder"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("StoreApi_GetInventory")] + public async Task _GetInventory([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/store/inventory")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("GetInventory"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("StoreApi_GetOrderById")] + public async Task _GetOrderById([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/store/order/{orderId}")]HttpRequest req, ExecutionContext context, [Range(1, 5)]long orderId) + { + var method = this.GetType().GetMethod("GetOrderById"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("StoreApi_PlaceOrder")] + public async Task _PlaceOrder([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/store/order")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("PlaceOrder"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + } +} + diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/UserApi.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/UserApi.cs new file mode 100644 index 00000000000..9ff559bce6c --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Functions/UserApi.cs @@ -0,0 +1,104 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Net; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.Azure.WebJobs; +using Microsoft.Azure.WebJobs.Extensions.Http; + +namespace Org.OpenAPITools.Apis +{ + public partial class UserApi + { + [FunctionName("UserApi_CreateUser")] + public async Task _CreateUser([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/user")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("CreateUser"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("UserApi_CreateUsersWithArrayInput")] + public async Task _CreateUsersWithArrayInput([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/user/createWithArray")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("CreateUsersWithArrayInput"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("UserApi_CreateUsersWithListInput")] + public async Task _CreateUsersWithListInput([HttpTrigger(AuthorizationLevel.Anonymous, "POST", Route = "/user/createWithList")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("CreateUsersWithListInput"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("UserApi_DeleteUser")] + public async Task _DeleteUser([HttpTrigger(AuthorizationLevel.Anonymous, "DELETE", Route = "/user/{username}")]HttpRequest req, ExecutionContext context, string username) + { + var method = this.GetType().GetMethod("DeleteUser"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("UserApi_GetUserByName")] + public async Task _GetUserByName([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/user/{username}")]HttpRequest req, ExecutionContext context, string username) + { + var method = this.GetType().GetMethod("GetUserByName"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("UserApi_LoginUser")] + public async Task _LoginUser([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/user/login")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("LoginUser"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("UserApi_LogoutUser")] + public async Task _LogoutUser([HttpTrigger(AuthorizationLevel.Anonymous, "GET", Route = "/user/logout")]HttpRequest req, ExecutionContext context) + { + var method = this.GetType().GetMethod("LogoutUser"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + + [FunctionName("UserApi_UpdateUser")] + public async Task _UpdateUser([HttpTrigger(AuthorizationLevel.Anonymous, "PUT", Route = "/user/{username}")]HttpRequest req, ExecutionContext context, string username) + { + var method = this.GetType().GetMethod("UpdateUser"); + + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); + } + } +} + diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/ApiResponse.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/ApiResponse.cs new file mode 100644 index 00000000000..031f72fa330 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/ApiResponse.cs @@ -0,0 +1,155 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Models +{ + /// + /// Describes the result of uploading an image resource + /// + [DataContract(Name = "ApiResponse")] + public partial class ApiResponse : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// code. + /// type. + /// message. + public ApiResponse(int code = default(int), string type = default(string), string message = default(string)) + { + this.Code = code; + this.Type = type; + this.Message = message; + } + + /// + /// Gets or Sets Code + /// + [DataMember(Name = "code", EmitDefaultValue = false)] + public int Code { get; set; } + + /// + /// Gets or Sets Type + /// + [DataMember(Name = "type", EmitDefaultValue = false)] + public string Type { get; set; } + + /// + /// Gets or Sets Message + /// + [DataMember(Name = "message", EmitDefaultValue = false)] + public string Message { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class ApiResponse {\n"); + sb.Append(" Code: ").Append(Code).Append("\n"); + sb.Append(" Type: ").Append(Type).Append("\n"); + sb.Append(" Message: ").Append(Message).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as ApiResponse); + } + + /// + /// Returns true if ApiResponse instances are equal + /// + /// Instance of ApiResponse to be compared + /// Boolean + public bool Equals(ApiResponse input) + { + if (input == null) + return false; + + return + ( + this.Code == input.Code || + this.Code.Equals(input.Code) + ) && + ( + this.Type == input.Type || + (this.Type != null && + this.Type.Equals(input.Type)) + ) && + ( + this.Message == input.Message || + (this.Message != null && + this.Message.Equals(input.Message)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = hashCode * 59 + this.Code.GetHashCode(); + if (this.Type != null) + hashCode = hashCode * 59 + this.Type.GetHashCode(); + if (this.Message != null) + hashCode = hashCode * 59 + this.Message.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Category.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Category.cs new file mode 100644 index 00000000000..ff645b073b9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Category.cs @@ -0,0 +1,146 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Models +{ + /// + /// A category for a pet + /// + [DataContract(Name = "Category")] + public partial class Category : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id. + /// name. + public Category(long id = default(long), string name = default(string)) + { + this.Id = id; + this.Name = name; + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Category {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Category); + } + + /// + /// Returns true if Category instances are equal + /// + /// Instance of Category to be compared + /// Boolean + public bool Equals(Category input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + this.Id.Equals(input.Id) + ) && + ( + this.Name == input.Name || + (this.Name != null && + this.Name.Equals(input.Name)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + // Name (string) pattern + Regex regexName = new Regex(@"^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$", RegexOptions.CultureInvariant); + if (false == regexName.Match(this.Name).Success) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, must match a pattern of " + regexName, new [] { "Name" }); + } + + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Order.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Order.cs new file mode 100644 index 00000000000..11bc4ed67be --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Order.cs @@ -0,0 +1,223 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Models +{ + /// + /// An order for a pets from the pet store + /// + [DataContract(Name = "Order")] + public partial class Order : IEquatable, IValidatableObject + { + /// + /// Order Status + /// + /// Order Status + [JsonConverter(typeof(StringEnumConverter))] + public enum StatusEnum + { + /// + /// Enum Placed for value: placed + /// + [EnumMember(Value = "placed")] + Placed = 1, + + /// + /// Enum Approved for value: approved + /// + [EnumMember(Value = "approved")] + Approved = 2, + + /// + /// Enum Delivered for value: delivered + /// + [EnumMember(Value = "delivered")] + Delivered = 3 + + } + + + /// + /// Order Status + /// + /// Order Status + [DataMember(Name = "status", EmitDefaultValue = false)] + public StatusEnum? Status { get; set; } + /// + /// Initializes a new instance of the class. + /// + /// id. + /// petId. + /// quantity. + /// shipDate. + /// Order Status. + /// complete (default to false). + public Order(long id = default(long), long petId = default(long), int quantity = default(int), DateTime shipDate = default(DateTime), StatusEnum? status = default(StatusEnum?), bool complete = false) + { + this.Id = id; + this.PetId = petId; + this.Quantity = quantity; + this.ShipDate = shipDate; + this.Status = status; + this.Complete = complete; + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets PetId + /// + [DataMember(Name = "petId", EmitDefaultValue = false)] + public long PetId { get; set; } + + /// + /// Gets or Sets Quantity + /// + [DataMember(Name = "quantity", EmitDefaultValue = false)] + public int Quantity { get; set; } + + /// + /// Gets or Sets ShipDate + /// + [DataMember(Name = "shipDate", EmitDefaultValue = false)] + public DateTime ShipDate { get; set; } + + /// + /// Gets or Sets Complete + /// + [DataMember(Name = "complete", EmitDefaultValue = true)] + public bool Complete { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Order {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" PetId: ").Append(PetId).Append("\n"); + sb.Append(" Quantity: ").Append(Quantity).Append("\n"); + sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Order); + } + + /// + /// Returns true if Order instances are equal + /// + /// Instance of Order to be compared + /// Boolean + public bool Equals(Order input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + this.Id.Equals(input.Id) + ) && + ( + this.PetId == input.PetId || + this.PetId.Equals(input.PetId) + ) && + ( + this.Quantity == input.Quantity || + this.Quantity.Equals(input.Quantity) + ) && + ( + this.ShipDate == input.ShipDate || + (this.ShipDate != null && + this.ShipDate.Equals(input.ShipDate)) + ) && + ( + this.Status == input.Status || + this.Status.Equals(input.Status) + ) && + ( + this.Complete == input.Complete || + this.Complete.Equals(input.Complete) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + hashCode = hashCode * 59 + this.PetId.GetHashCode(); + hashCode = hashCode * 59 + this.Quantity.GetHashCode(); + if (this.ShipDate != null) + hashCode = hashCode * 59 + this.ShipDate.GetHashCode(); + hashCode = hashCode * 59 + this.Status.GetHashCode(); + hashCode = hashCode * 59 + this.Complete.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Pet.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Pet.cs new file mode 100644 index 00000000000..6c4889298fa --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Pet.cs @@ -0,0 +1,238 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Models +{ + /// + /// A pet for sale in the pet store + /// + [DataContract(Name = "Pet")] + public partial class Pet : IEquatable, IValidatableObject + { + /// + /// pet status in the store + /// + /// pet status in the store + [JsonConverter(typeof(StringEnumConverter))] + public enum StatusEnum + { + /// + /// Enum Available for value: available + /// + [EnumMember(Value = "available")] + Available = 1, + + /// + /// Enum Pending for value: pending + /// + [EnumMember(Value = "pending")] + Pending = 2, + + /// + /// Enum Sold for value: sold + /// + [EnumMember(Value = "sold")] + Sold = 3 + + } + + + /// + /// pet status in the store + /// + /// pet status in the store + [DataMember(Name = "status", EmitDefaultValue = false)] + public StatusEnum? Status { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected Pet() { } + /// + /// Initializes a new instance of the class. + /// + /// id. + /// category. + /// name (required). + /// photoUrls (required). + /// tags. + /// pet status in the store. + public Pet(long id = default(long), Category category = default(Category), string name = default(string), List photoUrls = default(List), List tags = default(List), StatusEnum? status = default(StatusEnum?)) + { + // to ensure "name" is required (not null) + this.Name = name ?? throw new ArgumentNullException("name is a required property for Pet and cannot be null"); + // to ensure "photoUrls" is required (not null) + this.PhotoUrls = photoUrls ?? throw new ArgumentNullException("photoUrls is a required property for Pet and cannot be null"); + this.Id = id; + this.Category = category; + this.Tags = tags; + this.Status = status; + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets Category + /// + [DataMember(Name = "category", EmitDefaultValue = false)] + public Category Category { get; set; } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", IsRequired = true, EmitDefaultValue = false)] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [DataMember(Name = "photoUrls", IsRequired = true, EmitDefaultValue = false)] + public List PhotoUrls { get; set; } + + /// + /// Gets or Sets Tags + /// + [DataMember(Name = "tags", EmitDefaultValue = false)] + public List Tags { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Pet {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Tags: ").Append(Tags).Append("\n"); + sb.Append(" Status: ").Append(Status).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Pet); + } + + /// + /// Returns true if Pet instances are equal + /// + /// Instance of Pet to be compared + /// Boolean + public bool Equals(Pet input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + this.Id.Equals(input.Id) + ) && + ( + this.Category == input.Category || + (this.Category != null && + this.Category.Equals(input.Category)) + ) && + ( + this.Name == input.Name || + (this.Name != null && + this.Name.Equals(input.Name)) + ) && + ( + this.PhotoUrls == input.PhotoUrls || + this.PhotoUrls != null && + input.PhotoUrls != null && + this.PhotoUrls.SequenceEqual(input.PhotoUrls) + ) && + ( + this.Tags == input.Tags || + this.Tags != null && + input.Tags != null && + this.Tags.SequenceEqual(input.Tags) + ) && + ( + this.Status == input.Status || + this.Status.Equals(input.Status) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Category != null) + hashCode = hashCode * 59 + this.Category.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + if (this.PhotoUrls != null) + hashCode = hashCode * 59 + this.PhotoUrls.GetHashCode(); + if (this.Tags != null) + hashCode = hashCode * 59 + this.Tags.GetHashCode(); + hashCode = hashCode * 59 + this.Status.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Tag.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Tag.cs new file mode 100644 index 00000000000..f9fd7f6942e --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/Tag.cs @@ -0,0 +1,139 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Models +{ + /// + /// A tag for a pet + /// + [DataContract(Name = "Tag")] + public partial class Tag : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id. + /// name. + public Tag(long id = default(long), string name = default(string)) + { + this.Id = id; + this.Name = name; + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets Name + /// + [DataMember(Name = "name", EmitDefaultValue = false)] + public string Name { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class Tag {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Name: ").Append(Name).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as Tag); + } + + /// + /// Returns true if Tag instances are equal + /// + /// Instance of Tag to be compared + /// Boolean + public bool Equals(Tag input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + this.Id.Equals(input.Id) + ) && + ( + this.Name == input.Name || + (this.Name != null && + this.Name.Equals(input.Name)) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Name != null) + hashCode = hashCode * 59 + this.Name.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/User.cs b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/User.cs new file mode 100644 index 00000000000..45aa7bd2144 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/Models/User.cs @@ -0,0 +1,234 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Models +{ + /// + /// A User who is purchasing from the pet store + /// + [DataContract(Name = "User")] + public partial class User : IEquatable, IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// id. + /// username. + /// firstName. + /// lastName. + /// email. + /// password. + /// phone. + /// User Status. + public User(long id = default(long), string username = default(string), string firstName = default(string), string lastName = default(string), string email = default(string), string password = default(string), string phone = default(string), int userStatus = default(int)) + { + this.Id = id; + this.Username = username; + this.FirstName = firstName; + this.LastName = lastName; + this.Email = email; + this.Password = password; + this.Phone = phone; + this.UserStatus = userStatus; + } + + /// + /// Gets or Sets Id + /// + [DataMember(Name = "id", EmitDefaultValue = false)] + public long Id { get; set; } + + /// + /// Gets or Sets Username + /// + [DataMember(Name = "username", EmitDefaultValue = false)] + public string Username { get; set; } + + /// + /// Gets or Sets FirstName + /// + [DataMember(Name = "firstName", EmitDefaultValue = false)] + public string FirstName { get; set; } + + /// + /// Gets or Sets LastName + /// + [DataMember(Name = "lastName", EmitDefaultValue = false)] + public string LastName { get; set; } + + /// + /// Gets or Sets Email + /// + [DataMember(Name = "email", EmitDefaultValue = false)] + public string Email { get; set; } + + /// + /// Gets or Sets Password + /// + [DataMember(Name = "password", EmitDefaultValue = false)] + public string Password { get; set; } + + /// + /// Gets or Sets Phone + /// + [DataMember(Name = "phone", EmitDefaultValue = false)] + public string Phone { get; set; } + + /// + /// User Status + /// + /// User Status + [DataMember(Name = "userStatus", EmitDefaultValue = false)] + public int UserStatus { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + var sb = new StringBuilder(); + sb.Append("class User {\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); + sb.Append(" Username: ").Append(Username).Append("\n"); + sb.Append(" FirstName: ").Append(FirstName).Append("\n"); + sb.Append(" LastName: ").Append(LastName).Append("\n"); + sb.Append(" Email: ").Append(Email).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Phone: ").Append(Phone).Append("\n"); + sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as User); + } + + /// + /// Returns true if User instances are equal + /// + /// Instance of User to be compared + /// Boolean + public bool Equals(User input) + { + if (input == null) + return false; + + return + ( + this.Id == input.Id || + this.Id.Equals(input.Id) + ) && + ( + this.Username == input.Username || + (this.Username != null && + this.Username.Equals(input.Username)) + ) && + ( + this.FirstName == input.FirstName || + (this.FirstName != null && + this.FirstName.Equals(input.FirstName)) + ) && + ( + this.LastName == input.LastName || + (this.LastName != null && + this.LastName.Equals(input.LastName)) + ) && + ( + this.Email == input.Email || + (this.Email != null && + this.Email.Equals(input.Email)) + ) && + ( + this.Password == input.Password || + (this.Password != null && + this.Password.Equals(input.Password)) + ) && + ( + this.Phone == input.Phone || + (this.Phone != null && + this.Phone.Equals(input.Phone)) + ) && + ( + this.UserStatus == input.UserStatus || + this.UserStatus.Equals(input.UserStatus) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + hashCode = hashCode * 59 + this.Id.GetHashCode(); + if (this.Username != null) + hashCode = hashCode * 59 + this.Username.GetHashCode(); + if (this.FirstName != null) + hashCode = hashCode * 59 + this.FirstName.GetHashCode(); + if (this.LastName != null) + hashCode = hashCode * 59 + this.LastName.GetHashCode(); + if (this.Email != null) + hashCode = hashCode * 59 + this.Email.GetHashCode(); + if (this.Password != null) + hashCode = hashCode * 59 + this.Password.GetHashCode(); + if (this.Phone != null) + hashCode = hashCode * 59 + this.Phone.GetHashCode(); + hashCode = hashCode * 59 + this.UserStatus.GetHashCode(); + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/README.md b/samples/client/petstore/csharp-netcore-functions/generatedSrc/README.md new file mode 100644 index 00000000000..a531ad1e602 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/README.md @@ -0,0 +1,159 @@ +# Org.OpenAPITools - the C# library for the OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CsharpNetcoreFunctionsServerCodegen + + +## Frameworks supported +- .NET Core >=1.0 +- .NET Framework >=4.6 +- Mono/Xamarin >=vNext + + +## Dependencies + +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.11.7 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 12.0.3 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later + +The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: +``` +Install-Package RestSharp +Install-Package Newtonsoft.Json +Install-Package JsonSubTypes +Install-Package System.ComponentModel.Annotations +``` + +NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742). +NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406). + + +## Installation +Generate the DLL using your preferred tool (e.g. `dotnet build`) + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; +``` + +## Usage + +To use the API client with a HTTP proxy, setup a `System.Net.WebProxy` +```csharp +Configuration c = new Configuration(); +System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/"); +webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials; +c.Proxy = webProxy; +``` + + +## Getting Started + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Models; + +namespace Example +{ + public class Example + { + public static void Main() + { + + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io/v2"; + // Configure OAuth2 access token for authorization: petstore_auth + config.AccessToken = "YOUR_ACCESS_TOKEN"; + + var apiInstance = new PetApi(config); + var pet = new Pet(); // Pet | Pet object that needs to be added to the store + + try + { + // Add a new pet to the store + Pet result = apiInstance.AddPet(pet); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling PetApi.AddPet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**AddPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**DeletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**FindPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**FindPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**GetPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**UpdatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**UpdatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**UploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**DeleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**GetInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**GetOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**PlaceOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**CreateUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**CreateUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**CreateUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**DeleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**GetUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**LoginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**LogoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**UpdateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [Models.ApiResponse](docs/ApiResponse.md) + - [Models.Category](docs/Category.md) + - [Models.Order](docs/Order.md) + - [Models.Pet](docs/Pet.md) + - [Models.Tag](docs/Tag.md) + - [Models.User](docs/User.md) + + + +## Documentation for Authorization + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + diff --git a/samples/client/petstore/csharp-netcore-functions/generatedSrc/project.json b/samples/client/petstore/csharp-netcore-functions/generatedSrc/project.json new file mode 100644 index 00000000000..d5d3017c216 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/generatedSrc/project.json @@ -0,0 +1,12 @@ +{ + "supports": {}, + "dependencies": { + "FubarCoder.RestSharp.Portable.Core": "4.0.7", + "FubarCoder.RestSharp.Portable.HttpClient": "4.0.7", + "Newtonsoft.Json": "10.0.3", + "JsonSubTypes": "1.2.0" + }, + "frameworks": { + "netstandard1.3": {} + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore-functions/git_push.sh b/samples/client/petstore/csharp-netcore-functions/git_push.sh new file mode 100644 index 00000000000..ced3be2b0c7 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/git_push.sh @@ -0,0 +1,58 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-pestore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=`git remote` +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:${GIT_TOKEN}@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' + diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/ApiResponseTests.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/ApiResponseTests.cs new file mode 100644 index 00000000000..8a290fd090c --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/ApiResponseTests.cs @@ -0,0 +1,86 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Models; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing ApiResponse + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class ApiResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for ApiResponse + //private ApiResponse instance; + + public ApiResponseTests() + { + // TODO uncomment below to create an instance of ApiResponse + //instance = new ApiResponse(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of ApiResponse + /// + [Fact] + public void ApiResponseInstanceTest() + { + // TODO uncomment below to test "IsType" ApiResponse + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Code' + /// + [Fact] + public void CodeTest() + { + // TODO unit test for the property 'Code' + } + /// + /// Test the property 'Type' + /// + [Fact] + public void TypeTest() + { + // TODO unit test for the property 'Type' + } + /// + /// Test the property 'Message' + /// + [Fact] + public void MessageTest() + { + // TODO unit test for the property 'Message' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/CategoryTests.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/CategoryTests.cs new file mode 100644 index 00000000000..dd395f7d674 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/CategoryTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Models; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Category + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class CategoryTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Category + //private Category instance; + + public CategoryTests() + { + // TODO uncomment below to create an instance of Category + //instance = new Category(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Category + /// + [Fact] + public void CategoryInstanceTest() + { + // TODO uncomment below to test "IsType" Category + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/OrderTests.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/OrderTests.cs new file mode 100644 index 00000000000..d78afb0066d --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/OrderTests.cs @@ -0,0 +1,110 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Models; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Order + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class OrderTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Order + //private Order instance; + + public OrderTests() + { + // TODO uncomment below to create an instance of Order + //instance = new Order(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Order + /// + [Fact] + public void OrderInstanceTest() + { + // TODO uncomment below to test "IsType" Order + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'PetId' + /// + [Fact] + public void PetIdTest() + { + // TODO unit test for the property 'PetId' + } + /// + /// Test the property 'Quantity' + /// + [Fact] + public void QuantityTest() + { + // TODO unit test for the property 'Quantity' + } + /// + /// Test the property 'ShipDate' + /// + [Fact] + public void ShipDateTest() + { + // TODO unit test for the property 'ShipDate' + } + /// + /// Test the property 'Status' + /// + [Fact] + public void StatusTest() + { + // TODO unit test for the property 'Status' + } + /// + /// Test the property 'Complete' + /// + [Fact] + public void CompleteTest() + { + // TODO unit test for the property 'Complete' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/PetTests.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/PetTests.cs new file mode 100644 index 00000000000..b444a6448fc --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/PetTests.cs @@ -0,0 +1,110 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Models; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Pet + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class PetTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Pet + //private Pet instance; + + public PetTests() + { + // TODO uncomment below to create an instance of Pet + //instance = new Pet(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Pet + /// + [Fact] + public void PetInstanceTest() + { + // TODO uncomment below to test "IsType" Pet + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Category' + /// + [Fact] + public void CategoryTest() + { + // TODO unit test for the property 'Category' + } + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + /// + /// Test the property 'PhotoUrls' + /// + [Fact] + public void PhotoUrlsTest() + { + // TODO unit test for the property 'PhotoUrls' + } + /// + /// Test the property 'Tags' + /// + [Fact] + public void TagsTest() + { + // TODO unit test for the property 'Tags' + } + /// + /// Test the property 'Status' + /// + [Fact] + public void StatusTest() + { + // TODO unit test for the property 'Status' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/TagTests.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/TagTests.cs new file mode 100644 index 00000000000..141398d0380 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/TagTests.cs @@ -0,0 +1,78 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Models; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing Tag + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class TagTests : IDisposable + { + // TODO uncomment below to declare an instance variable for Tag + //private Tag instance; + + public TagTests() + { + // TODO uncomment below to create an instance of Tag + //instance = new Tag(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of Tag + /// + [Fact] + public void TagInstanceTest() + { + // TODO uncomment below to test "IsType" Tag + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Name' + /// + [Fact] + public void NameTest() + { + // TODO unit test for the property 'Name' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/UserTests.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/UserTests.cs new file mode 100644 index 00000000000..3f0d780b966 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools.Test/Models/UserTests.cs @@ -0,0 +1,126 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Apis; +using Org.OpenAPITools.Models; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing User + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class UserTests : IDisposable + { + // TODO uncomment below to declare an instance variable for User + //private User instance; + + public UserTests() + { + // TODO uncomment below to create an instance of User + //instance = new User(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of User + /// + [Fact] + public void UserInstanceTest() + { + // TODO uncomment below to test "IsType" User + //Assert.IsType(instance); + } + + + /// + /// Test the property 'Id' + /// + [Fact] + public void IdTest() + { + // TODO unit test for the property 'Id' + } + /// + /// Test the property 'Username' + /// + [Fact] + public void UsernameTest() + { + // TODO unit test for the property 'Username' + } + /// + /// Test the property 'FirstName' + /// + [Fact] + public void FirstNameTest() + { + // TODO unit test for the property 'FirstName' + } + /// + /// Test the property 'LastName' + /// + [Fact] + public void LastNameTest() + { + // TODO unit test for the property 'LastName' + } + /// + /// Test the property 'Email' + /// + [Fact] + public void EmailTest() + { + // TODO unit test for the property 'Email' + } + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + /// + /// Test the property 'Phone' + /// + [Fact] + public void PhoneTest() + { + // TODO unit test for the property 'Phone' + } + /// + /// Test the property 'UserStatus' + /// + [Fact] + public void UserStatusTest() + { + // TODO unit test for the property 'UserStatus' + } + + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiClient.cs new file mode 100644 index 00000000000..4f68a59871e --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiClient.cs @@ -0,0 +1,860 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; +using RestSharp; +using RestSharp.Deserializers; +using RestSharpMethod = RestSharp.Method; +using Polly; + +namespace Org.OpenAPITools.Client +{ + /// + /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer + { + private readonly IReadableConfiguration _configuration; + private static readonly string _contentType = "application/json"; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is Org.OpenAPITools.Models.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return ((Org.OpenAPITools.Models.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public T Deserialize(IRestResponse response) + { + var result = (T)Deserialize(response, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal object Deserialize(IRestResponse response, Type type) + { + if (type == typeof(byte[])) // return byte array + { + return response.RawBytes; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = response.RawBytes; + if (response.Headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in response.Headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(response.Content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public string RootElement { get; set; } + public string Namespace { get; set; } + public string DateFormat { get; set; } + + public string ContentType + { + get { return _contentType; } + set { throw new InvalidOperationException("Not allowed to set content type."); } + } + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), + /// encapsulating general REST accessor use cases. + /// + public partial class ApiClient : ISynchronousClient, IAsynchronousClient + { + private readonly string _baseUrl; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accomodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(IRestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(IRestRequest request, IRestResponse response); + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + public ApiClient() + { + _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + } + + /// + /// Initializes a new instance of the + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + _baseUrl = basePath; + } + + /// + /// Constructs the RestSharp version of an http method + /// + /// Swagger Client Custom HttpMethod + /// RestSharp's HttpMethod instance. + /// + private RestSharpMethod Method(HttpMethod method) + { + RestSharpMethod other; + switch (method) + { + case HttpMethod.Get: + other = RestSharpMethod.GET; + break; + case HttpMethod.Post: + other = RestSharpMethod.POST; + break; + case HttpMethod.Put: + other = RestSharpMethod.PUT; + break; + case HttpMethod.Delete: + other = RestSharpMethod.DELETE; + break; + case HttpMethod.Head: + other = RestSharpMethod.HEAD; + break; + case HttpMethod.Options: + other = RestSharpMethod.OPTIONS; + break; + case HttpMethod.Patch: + other = RestSharpMethod.PATCH; + break; + default: + throw new ArgumentOutOfRangeException("method", method, null); + } + + return other; + } + + /// + /// Provides all logic for constructing a new RestSharp . + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the RestSharp request. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new RestRequest instance. + /// + private RestRequest NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + RestRequest request = new RestRequest(Method(method)) + { + Resource = path, + JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) + }; + + if (options.PathParameters != null) + { + foreach (var pathParam in options.PathParameters) + { + request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); + } + } + + if (options.QueryParameters != null) + { + foreach (var queryParam in options.QueryParameters) + { + foreach (var value in queryParam.Value) + { + request.AddQueryParameter(queryParam.Key, value); + } + } + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.AddHeader(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + request.AddHeader(headerParam.Key, value); + } + } + } + + if (options.FormParameters != null) + { + foreach (var formParam in options.FormParameters) + { + request.AddParameter(formParam.Key, formParam.Value); + } + } + + if (options.Data != null) + { + if (options.Data is Stream stream) + { + var contentType = "application/octet-stream"; + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes[0]; + } + + var bytes = ClientUtils.ReadAsBytes(stream); + request.AddParameter(contentType, bytes, ParameterType.RequestBody); + } + else + { + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) + { + request.RequestFormat = DataFormat.Json; + } + else + { + // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. + } + } + else + { + // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. + request.RequestFormat = DataFormat.Json; + } + + request.AddJsonBody(options.Data); + } + } + + if (options.FileParameters != null) + { + foreach (var fileParam in options.FileParameters) + { + var bytes = ClientUtils.ReadAsBytes(fileParam.Value); + var fileStream = fileParam.Value as FileStream; + if (fileStream != null) + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); + else + request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); + } + } + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + request.AddCookie(cookie.Name, cookie.Value); + } + } + + return request; + } + + private ApiResponse ToApiResponse(IRestResponse response) + { + T result = response.Data; + string rawContent = response.Content; + + var transformed = new ApiResponse(response.StatusCode, new Multimap(), result, rawContent) + { + ErrorText = response.ErrorMessage, + Cookies = new List() + }; + + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.Cookies != null) + { + foreach (var responseCookies in response.Cookies) + { + transformed.Cookies.Add( + new Cookie( + responseCookies.Name, + responseCookies.Value, + responseCookies.Path, + responseCookies.Domain) + ); + } + } + + return transformed; + } + + private ApiResponse Exec(RestRequest req, IReadableConfiguration configuration) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = client.Execute(req); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + private async Task> ExecAsync(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + RestClient client = new RestClient(_baseUrl); + + client.ClearHandlers(); + var existingDeserializer = req.JsonSerializer as IDeserializer; + if (existingDeserializer != null) + { + client.AddHandler("application/json", () => existingDeserializer); + client.AddHandler("text/json", () => existingDeserializer); + client.AddHandler("text/x-json", () => existingDeserializer); + client.AddHandler("text/javascript", () => existingDeserializer); + client.AddHandler("*+json", () => existingDeserializer); + } + else + { + var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); + client.AddHandler("application/json", () => customDeserializer); + client.AddHandler("text/json", () => customDeserializer); + client.AddHandler("text/x-json", () => customDeserializer); + client.AddHandler("text/javascript", () => customDeserializer); + client.AddHandler("*+json", () => customDeserializer); + } + + var xmlDeserializer = new XmlDeserializer(); + client.AddHandler("application/xml", () => xmlDeserializer); + client.AddHandler("text/xml", () => xmlDeserializer); + client.AddHandler("*+xml", () => xmlDeserializer); + client.AddHandler("*", () => xmlDeserializer); + + client.Timeout = configuration.Timeout; + + if (configuration.Proxy != null) + { + client.Proxy = configuration.Proxy; + } + + if (configuration.UserAgent != null) + { + client.UserAgent = configuration.UserAgent; + } + + if (configuration.ClientCertificates != null) + { + client.ClientCertificates = configuration.ClientCertificates; + } + + InterceptRequest(req); + + IRestResponse response; + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(req, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse + { + Request = req, + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(req, cancellationToken).ConfigureAwait(false); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Org.OpenAPITools.Models.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + + InterceptResponse(req, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken); + } + #endregion IAsynchronousClient + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Patch, path, options, config), config); + } + #endregion ISynchronousClient + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiException.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 00000000000..dcc378ad208 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiException.cs @@ -0,0 +1,68 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public object ErrorContent { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() { } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + /// HTTP Headers. + public ApiException(int errorCode, string message, object errorContent = null, Multimap headers = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + this.Headers = headers; + } + } + +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiResponse.cs new file mode 100644 index 00000000000..6d91a6f7a47 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -0,0 +1,166 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// The content of this response + /// + Object Content { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + Multimap Headers { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + List Cookies { get; set; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + } + + /// + /// API Response + /// + public class ApiResponse : IApiResponse + { + #region Properties + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + public string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + public List Cookies { get; set; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The data type of + /// + public object Content + { + get { return Data; } + } + + /// + /// The raw content + /// + public string RawContent { get; } + + #endregion Properties + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data, string rawContent) + { + StatusCode = statusCode; + Headers = headers; + Data = data; + RawContent = rawContent; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data) : this(statusCode, headers, data, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null) + { + } + + #endregion Constructors + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ClientUtils.cs new file mode 100644 index 00000000000..e23537db3c2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -0,0 +1,229 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Text; +using System.Text.RegularExpressions; + +namespace Org.OpenAPITools.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// Convert params to key/value pairs. + /// Use collectionFormat to properly format lists and collections. + /// + /// The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi + /// Key name. + /// Value object. + /// A multimap of keys with 1..n associated values. + public static Multimap ParameterToMultiMap(string collectionFormat, string name, object value) + { + var parameters = new Multimap(); + + if (value is ICollection collection && collectionFormat == "multi") + { + foreach (var item in collection) + { + parameters.Add(name, ParameterToString(item)); + } + } + else if (value is IDictionary dictionary) + { + if(collectionFormat == "deepObject") { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value)); + } + } + else { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value)); + } + } + } + else + { + parameters.Add(name, ParameterToString(value)); + } + + return parameters; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// An optional configuration instance, providing formatting options used in processing. + /// Formatted string. + public static string ParameterToString(object obj, IReadableConfiguration configuration = null) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) + return string.Join(",", collection.Cast()); + + return Convert.ToString(obj, CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// 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) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/Configuration.cs new file mode 100644 index 00000000000..896bd754ea5 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/Configuration.cs @@ -0,0 +1,515 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "1.0.0"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var status = (int)response.StatusCode; + if (status >= 400) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.RawContent), + response.RawContent, response.Headers); + } + return null; + }; + + #endregion Static Members + + #region Private Members + + /// + /// Defines the base path of the target API server. + /// Example: http://localhost:3000/v1/ + /// + private string _basePath; + + /// + /// Gets or sets the API key based on the authentication name. + /// This is the key and value comprising the "secret" for acessing an API. + /// + /// The API key. + private IDictionary _apiKey; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + + /// + /// Gets or sets the servers defined in the OpenAPI spec. + /// + /// The servers + private IList> _servers; + #endregion Private Members + + #region Constructors + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration() + { + Proxy = null; + UserAgent = "OpenAPI-Generator/1.0.0/csharp"; + BasePath = "http://petstore.swagger.io/v2"; + DefaultHeaders = new ConcurrentDictionary(); + ApiKey = new ConcurrentDictionary(); + ApiKeyPrefix = new ConcurrentDictionary(); + Servers = new List>() + { + { + new Dictionary { + {"url", "http://petstore.swagger.io/v2"}, + {"description", "No description provided"}, + } + } + }; + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration( + IDictionary defaultHeaders, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "http://petstore.swagger.io/v2") : this() + { + if (string.IsNullOrWhiteSpace(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeaders == null) + throw new ArgumentNullException("defaultHeaders"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeaders) + { + DefaultHeaders.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + #endregion Constructors + + #region Properties + + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath { + get { return _basePath; } + set { _basePath = value; } + } + + /// + /// Gets or sets the default header. + /// + [Obsolete("Use DefaultHeaders instead.")] + public virtual IDictionary DefaultHeader + { + get + { + return DefaultHeaders; + } + set + { + DefaultHeaders = value; + } + } + + /// + /// Gets or sets the default headers. + /// + public virtual IDictionary DefaultHeaders { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout { get; set; } + + /// + /// Gets or sets the proxy + /// + /// Proxy. + public virtual WebProxy Proxy { get; set; } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + string apiKeyValue; + ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); + string apiKeyPrefix; + if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) + { + return apiKeyPrefix + " " + apiKeyValue; + } + + return apiKeyValue; + } + + /// + /// Gets or sets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + public X509CertificateCollection ClientCertificates { get; set; } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// This helper property simplifies code generation. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + _tempFolderPath = Path.GetTempPath(); + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + { + _tempFolderPath = value; + } + else + { + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + } + + /// + /// Gets or sets the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// Whatever you set here will be prepended to the value defined in AddApiKey. + /// + /// An example invocation here might be: + /// + /// ApiKeyPrefix["Authorization"] = "Bearer"; + /// + /// … where ApiKey["Authorization"] would then be used to set the value of your bearer token. + /// + /// + /// OAuth2 workflows should set tokens via AccessToken. + /// + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + + /// + /// Gets or sets the servers. + /// + /// The servers. + public virtual IList> Servers + { + get { return _servers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Servers may not be null."); + } + _servers = value; + } + } + + /// + /// Returns URL based on server settings without providing values + /// for the variables + /// + /// Array index of the server settings. + /// The server URL. + public string GetServerUrl(int index) + { + return GetServerUrl(index, null); + } + + /// + /// Returns URL based on server settings. + /// + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + public string GetServerUrl(int index, Dictionary inputVariables) + { + if (index < 0 || index >= Servers.Count) + { + throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {Servers.Count}."); + } + + if (inputVariables == null) + { + inputVariables = new Dictionary(); + } + + IReadOnlyDictionary server = Servers[index]; + string url = (string)server["url"]; + + // go through variable and assign a value + foreach (KeyValuePair variable in (IReadOnlyDictionary)server["variables"]) + { + + IReadOnlyDictionary serverVariables = (IReadOnlyDictionary)(variable.Value); + + if (inputVariables.ContainsKey(variable.Key)) + { + if (((List)serverVariables["enum_values"]).Contains(inputVariables[variable.Key])) + { + url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]); + } + else + { + throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List)serverVariables["enum_values"]}"); + } + } + else + { + // use defualt value + url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]); + } + } + + return url; + } + + #endregion Properties + + #region Methods + + /// + /// Returns a string with essential information for debugging. + /// + public static string ToDebugReport() + { + string report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: 1.0.0\n"; + report += " SDK Package Version: 1.0.0\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + + #region Static Members + /// + /// Merge configurations. + /// + /// First configuration. + /// Second configuration. + /// Merged configuration. + public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second) + { + if (second == null) return first ?? GlobalConfiguration.Instance; + + Dictionary apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value; + foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value; + foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value; + + var config = new Configuration + { + ApiKey = apiKey, + ApiKeyPrefix = apiKeyPrefix, + DefaultHeaders = defaultHeaders, + BasePath = second.BasePath ?? first.BasePath, + Timeout = second.Timeout, + Proxy = second.Proxy ?? first.Proxy, + UserAgent = second.UserAgent ?? first.UserAgent, + Username = second.Username ?? first.Username, + Password = second.Password ?? first.Password, + AccessToken = second.AccessToken ?? first.AccessToken, + TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, + DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat + }; + return config; + } + #endregion Static Members + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ExceptionFactory.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ExceptionFactory.cs new file mode 100644 index 00000000000..6ae2a10aae4 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ExceptionFactory.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IApiResponse response); +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/GlobalConfiguration.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/GlobalConfiguration.cs new file mode 100644 index 00000000000..e1c00c89a03 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/GlobalConfiguration.cs @@ -0,0 +1,67 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// provides a compile-time extension point for globally configuring + /// API Clients. + /// + /// + /// A customized implementation via partial class may reside in another file and may + /// be excluded from automatic generation via a .openapi-generator-ignore file. + /// + public partial class GlobalConfiguration : Configuration + { + #region Private Members + + private static readonly object GlobalConfigSync = new { }; + private static IReadableConfiguration _globalConfiguration; + + #endregion Private Members + + #region Constructors + + /// + private GlobalConfiguration() + { + } + + /// + public GlobalConfiguration(IDictionary defaultHeader, IDictionary apiKey, IDictionary apiKeyPrefix, string basePath = "http://localhost:3000/api") : base(defaultHeader, apiKey, apiKeyPrefix, basePath) + { + } + + static GlobalConfiguration() + { + Instance = new GlobalConfiguration(); + } + + #endregion Constructors + + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static IReadableConfiguration Instance + { + get { return _globalConfiguration; } + set + { + lock (GlobalConfigSync) + { + _globalConfiguration = value; + } + } + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/HttpMethod.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/HttpMethod.cs new file mode 100644 index 00000000000..1dd692d8cfb --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/HttpMethod.cs @@ -0,0 +1,33 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client +{ + /// + /// Http methods supported by swagger + /// + public enum HttpMethod + { + /// HTTP GET request. + Get, + /// HTTP POST request. + Post, + /// HTTP PUT request. + Put, + /// HTTP DELETE request. + Delete, + /// HTTP HEAD request. + Head, + /// HTTP OPTIONS request. + Options, + /// HTTP PATCH request. + Patch + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IApiAccessor.cs new file mode 100644 index 00000000000..c8a78e995ce --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -0,0 +1,37 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + IReadableConfiguration Configuration { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + string GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IAsynchronousClient.cs new file mode 100644 index 00000000000..066d9b39482 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -0,0 +1,100 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; + +namespace Org.OpenAPITools.Client +{ + /// + /// Contract for Asynchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface IAsynchronousClient + { + /// + /// Executes a non-blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IReadableConfiguration.cs new file mode 100644 index 00000000000..00bedba8ee2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -0,0 +1,115 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Net; +using System.Security.Cryptography.X509Certificates; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a readable-only configuration contract. + /// + public interface IReadableConfiguration + { + /// + /// Gets the access token. + /// + /// Access token. + string AccessToken { get; } + + /// + /// Gets the API key. + /// + /// API key. + IDictionary ApiKey { get; } + + /// + /// Gets the API key prefix. + /// + /// API key prefix. + IDictionary ApiKeyPrefix { get; } + + /// + /// Gets the base path. + /// + /// Base path. + string BasePath { get; } + + /// + /// Gets the date time format. + /// + /// Date time foramt. + string DateTimeFormat { get; } + + /// + /// Gets the default header. + /// + /// Default header. + [Obsolete("Use DefaultHeaders instead.")] + IDictionary DefaultHeader { get; } + + /// + /// Gets the default headers. + /// + /// Default headers. + IDictionary DefaultHeaders { get; } + + /// + /// Gets the temp folder path. + /// + /// Temp folder path. + string TempFolderPath { get; } + + /// + /// Gets the HTTP connection timeout (in milliseconds) + /// + /// HTTP connection timeout. + int Timeout { get; } + + /// + /// Gets the proxy. + /// + /// Proxy. + WebProxy Proxy { get; } + + /// + /// Gets the user agent. + /// + /// User agent. + string UserAgent { get; } + + /// + /// Gets the username. + /// + /// Username. + string Username { get; } + + /// + /// Gets the password. + /// + /// Password. + string Password { get; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + + /// + /// Gets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + X509CertificateCollection ClientCertificates { get; } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ISynchronousClient.cs new file mode 100644 index 00000000000..3910f6d68ce --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -0,0 +1,93 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.IO; + +namespace Org.OpenAPITools.Client +{ + /// + /// Contract for Synchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface ISynchronousClient + { + /// + /// Executes a blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/Multimap.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/Multimap.cs new file mode 100644 index 00000000000..966d634a50b --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/Multimap.cs @@ -0,0 +1,295 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A dictionary in which one key has many associated values. + /// + /// The type of the key + /// The type of the value associated with the key. + public class Multimap : IDictionary> + { + #region Private Fields + + private readonly Dictionary> _dictionary; + + #endregion Private Fields + + #region Constructors + + /// + /// Empty Constructor. + /// + public Multimap() + { + _dictionary = new Dictionary>(); + } + + /// + /// Constructor with comparer. + /// + /// + public Multimap(IEqualityComparer comparer) + { + _dictionary = new Dictionary>(comparer); + } + + #endregion Constructors + + #region Enumerators + + /// + /// To get the enumerator. + /// + /// Enumerator + public IEnumerator>> GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + /// + /// To get the enumerator. + /// + /// Enumerator + IEnumerator IEnumerable.GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + #endregion Enumerators + + #region Public Members + /// + /// Add values to Multimap + /// + /// Key value pair + public void Add(KeyValuePair> item) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + + /// + /// Add Multimap to Multimap + /// + /// Multimap + public void Add(Multimap multimap) + { + foreach (var item in multimap) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + + /// + /// Clear Multimap + /// + public void Clear() + { + _dictionary.Clear(); + } + + /// + /// Determines whether Multimap contains the specified item. + /// + /// Key value pair + /// Method needs to be implemented + /// true if the Multimap contains the item; otherwise, false. + public bool Contains(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Copy items of the Multimap to an array, + /// starting at a particular array index. + /// + /// The array that is the destination of the items copied + /// from Multimap. The array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + /// Method needs to be implemented + public void CopyTo(KeyValuePair>[] array, int arrayIndex) + { + throw new NotImplementedException(); + } + + /// + /// Removes the specified item from the Multimap. + /// + /// Key value pair + /// true if the item is successfully removed; otherwise, false. + /// Method needs to be implemented + public bool Remove(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Gets the number of items contained in the Multimap. + /// + public int Count => _dictionary.Count; + + /// + /// Gets a value indicating whether the Multimap is read-only. + /// + public bool IsReadOnly => false; + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add the value to Multimap. + public void Add(TKey key, IList value) + { + if (value != null && value.Count > 0) + { + if (_dictionary.TryGetValue(key, out var list)) + { + foreach (var k in value) list.Add(k); + } + else + { + list = new List(value); + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + } + + /// + /// Determines whether the Multimap contains an item with the specified key. + /// + /// The key to locate in the Multimap. + /// true if the Multimap contains an item with + /// the key; otherwise, false. + public bool ContainsKey(TKey key) + { + return _dictionary.ContainsKey(key); + } + + /// + /// Removes item with the specified key from the Multimap. + /// + /// The key to locate in the Multimap. + /// true if the item is successfully removed; otherwise, false. + public bool Remove(TKey key) + { + return TryRemove(key, out var _); + } + + /// + /// Gets the value associated with the specified key. + /// + /// The key whose value to get. + /// When this method returns, the value associated with the specified key, if the + /// key is found; otherwise, the default value for the type of the value parameter. + /// This parameter is passed uninitialized. + /// true if the object that implements Multimap contains + /// an item with the specified key; otherwise, false. + public bool TryGetValue(TKey key, out IList value) + { + return _dictionary.TryGetValue(key, out value); + } + + /// + /// Gets or sets the item with the specified key. + /// + /// The key of the item to get or set. + /// The value of the specified key. + public IList this[TKey key] + { + get => _dictionary[key]; + set => _dictionary[key] = value; + } + + /// + /// Gets a System.Collections.Generic.ICollection containing the keys of the Multimap. + /// + public ICollection Keys => _dictionary.Keys; + + /// + /// Gets a System.Collections.Generic.ICollection containing the values of the Multimap. + /// + public ICollection> Values => _dictionary.Values; + + /// + /// Copy the items of the Multimap to an System.Array, + /// starting at a particular System.Array index. + /// + /// The one-dimensional System.Array that is the destination of the items copied + /// from Multimap. The System.Array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + public void CopyTo(Array array, int index) + { + ((ICollection)_dictionary).CopyTo(array, index); + } + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add value to Multimap. + public void Add(TKey key, TValue value) + { + if (value != null) + { + if (_dictionary.TryGetValue(key, out var list)) + { + list.Add(value); + } + else + { + list = new List { value }; + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add value to Multimap."); + } + } + } + + #endregion Public Members + + #region Private Members + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryRemove(TKey key, out IList value) + { + _dictionary.TryGetValue(key, out value); + return _dictionary.Remove(key); + } + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryAdd(TKey key, IList value) + { + try + { + _dictionary.Add(key, value); + } + catch (ArgumentException) + { + return false; + } + + return true; + } + #endregion Private Members + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs new file mode 100644 index 00000000000..dcc79edd944 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs @@ -0,0 +1,29 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using Newtonsoft.Json.Converters; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/RequestOptions.cs new file mode 100644 index 00000000000..c6b3ccc38f2 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Dictionary FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Dictionary(); + Cookies = new List(); + } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/RetryConfiguration.cs new file mode 100644 index 00000000000..c93633a36d9 --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -0,0 +1,21 @@ +using Polly; +using RestSharp; + +namespace Org.OpenAPITools.Client +{ + /// + /// Configuration class to set the polly retry policies to be applied to the requests. + /// + public class RetryConfiguration + { + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } + } +} diff --git a/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Models/AbstractOpenAPISchema.cs b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Models/AbstractOpenAPISchema.cs new file mode 100644 index 00000000000..38e023162dd --- /dev/null +++ b/samples/client/petstore/csharp-netcore-functions/src/Org.OpenAPITools/Models/AbstractOpenAPISchema.cs @@ -0,0 +1,76 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Org.OpenAPITools.Models +{ + /// + /// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification + /// + public abstract partial class AbstractOpenAPISchema + { + /// + /// Custom JSON serializer + /// + static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Error, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Custom JSON serializer for objects with additional properties + /// + static public readonly JsonSerializerSettings AdditionalPropertiesSerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Ignore, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Gets or Sets the actual instance + /// + public abstract Object ActualInstance { get; set; } + + /// + /// Gets or Sets IsNullable to indicate whether the instance is nullable + /// + public bool IsNullable { get; protected set; } + + /// + /// Gets or Sets the schema type, which can be either `oneOf` or `anyOf` + /// + public string SchemaType { get; protected set; } + + /// + /// Converts the instance into JSON string. + /// + public abstract string ToJson(); + } +}