diff --git a/.travis.yml b/.travis.yml index ab73003e51f94..51223465035c8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -24,6 +24,7 @@ install: - export LD_LIBRARY_PATH=$HOME/.local/lib/:$LD_LIBRARY_PATH # Install npm - curl -sSL https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.sh | sh && source ~/.dnx/dnvm/dnvm.sh && dnvm upgrade + - rm -rf ~/.nvm && git clone https://github.com/creationix/nvm.git ~/.nvm && (cd ~/.nvm && git checkout `git describe --abbrev=0 --tags`) && source ~/.nvm/nvm.sh && nvm install 4 - npm install -g npm@'>=1.4.3' - npm install # Install ruby dependencies @@ -34,7 +35,8 @@ install: # Install android SDK - mkdir android - wget -qO- "http://dl.google.com/android/android-sdk_r23.0.2-linux.tgz" | tar -zxv -C ./android - - echo y | ./android/android-sdk-linux/tools/android update sdk --all --filter platform-tools,android-23,build-tools-23.0.1,extra-android-support,extra-android-m2repository,extra-google-m2repository --no-ui --force + - echo y | ./android/android-sdk-linux/tools/android update sdk --all --filter platform-tools,android-23,build-tools-23.0.1 --no-ui --force + - echo y | ./android/android-sdk-linux/tools/android update sdk --all --filter extra-android-support,extra-android-m2repository,extra-google-m2repository --no-ui --force - export ANDROID_HOME=`pwd`/android/android-sdk-linux script: - dnvm install 1.0.0-rc1-final -r mono @@ -49,4 +51,4 @@ after_script: - cat TestResults/*.log notifications: slack: - secure: d0PFVLcyqcMxNtmZ8JaEpIBzXbUbZCgKs8QtBB5qEIXDnxflSR3AhczlILNhTBKtMEBlwVzsz65yP09XcmvB6xpAfJbHqSRzk2frKa5viPcAD8Wr/NYamt9/UiTCsnql8MqzjVy0tLdMscXKRmsUey4YF570zl0b7gAbq7XTqxM= \ No newline at end of file + secure: d0PFVLcyqcMxNtmZ8JaEpIBzXbUbZCgKs8QtBB5qEIXDnxflSR3AhczlILNhTBKtMEBlwVzsz65yP09XcmvB6xpAfJbHqSRzk2frKa5viPcAD8Wr/NYamt9/UiTCsnql8MqzjVy0tLdMscXKRmsUey4YF570zl0b7gAbq7XTqxM= diff --git a/AutoRest.sln b/AutoRest.sln index f616c9ac420d0..b11b89d798ca5 100644 --- a/AutoRest.sln +++ b/AutoRest.sln @@ -118,6 +118,12 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoRest.Modeler.CompositeS EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoRest.Modeler.CompositeSwagger.Tests", "AutoRest\Modelers\CompositeSwagger.Tests\AutoRest.Modeler.CompositeSwagger.Tests.csproj", "{DA37E6A9-5D59-45A3-A809-ABA85031C369}" EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AzureResourceSchema", "AzureResourceSchema", "{B6A1FC1E-0779-4900-84EE-262DD0E53FF4}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoRest.Generator.AzureResourceSchema", "AutoRest\Generators\AzureResourceSchema\AzureResourceSchema\AutoRest.Generator.AzureResourceSchema.csproj", "{654344A5-0556-49C7-BFB3-59676D7440D3}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoRest.Generator.AzureResourceSchema.Tests", "AutoRest\Generators\AzureResourceSchema\AzureResourceSchema.Tests\AutoRest.Generator.AzureResourceSchema.Tests.csproj", "{1C3B4A33-E045-4C8F-9202-1B651A686567}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Net45-Debug|Any CPU = Net45-Debug|Any CPU @@ -366,6 +372,22 @@ Global {DA37E6A9-5D59-45A3-A809-ABA85031C369}.Portable-Debug|Any CPU.Build.0 = Portable-Debug|Any CPU {DA37E6A9-5D59-45A3-A809-ABA85031C369}.Portable-Release|Any CPU.ActiveCfg = Portable-Release|Any CPU {DA37E6A9-5D59-45A3-A809-ABA85031C369}.Portable-Release|Any CPU.Build.0 = Portable-Release|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Net45-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Net45-Debug|Any CPU.Build.0 = Debug|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Net45-Release|Any CPU.ActiveCfg = Release|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Net45-Release|Any CPU.Build.0 = Release|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Portable-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Portable-Debug|Any CPU.Build.0 = Debug|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Portable-Release|Any CPU.ActiveCfg = Release|Any CPU + {654344A5-0556-49C7-BFB3-59676D7440D3}.Portable-Release|Any CPU.Build.0 = Release|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Net45-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Net45-Debug|Any CPU.Build.0 = Debug|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Net45-Release|Any CPU.ActiveCfg = Release|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Net45-Release|Any CPU.Build.0 = Release|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Portable-Debug|Any CPU.ActiveCfg = Debug|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Portable-Debug|Any CPU.Build.0 = Debug|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Portable-Release|Any CPU.ActiveCfg = Release|Any CPU + {1C3B4A33-E045-4C8F-9202-1B651A686567}.Portable-Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -407,5 +429,8 @@ Global {74BE0601-FF65-4B46-8A8B-E670056061C4} = {74F7C659-952F-400C-839F-90BED9BB66C3} {31AEC9B5-35C9-4FEA-8420-4C34D3FEAAC8} = {02144BF6-4489-4AFC-9B2D-0306C3DD3C19} {DA37E6A9-5D59-45A3-A809-ABA85031C369} = {02144BF6-4489-4AFC-9B2D-0306C3DD3C19} + {B6A1FC1E-0779-4900-84EE-262DD0E53FF4} = {EF9E346D-70C6-45F5-8FF9-9B734F4A1298} + {654344A5-0556-49C7-BFB3-59676D7440D3} = {B6A1FC1E-0779-4900-84EE-262DD0E53FF4} + {1C3B4A33-E045-4C8F-9202-1B651A686567} = {B6A1FC1E-0779-4900-84EE-262DD0E53FF4} EndGlobalSection EndGlobal diff --git a/AutoRest/AutoRest.Core.Tests/CodeGeneratorsTests.cs b/AutoRest/AutoRest.Core.Tests/CodeGeneratorsTests.cs index c58c81e4e6b0c..8cadb3f6414f4 100644 --- a/AutoRest/AutoRest.Core.Tests/CodeGeneratorsTests.cs +++ b/AutoRest/AutoRest.Core.Tests/CodeGeneratorsTests.cs @@ -86,8 +86,11 @@ public void OutputToSingleFile() }; string path = Path.Combine(settings.OutputDirectory, "test.file.cs"); + string existingContents = "this is dummy"; + _fileSystem.VirtualStore[path] = new StringBuilder(existingContents); var codeGenerator = new SampleCodeGenerator(settings); codeGenerator.Generate(new ServiceClient()).GetAwaiter().GetResult(); + Assert.DoesNotContain(existingContents, _fileSystem.VirtualStore[path].ToString()); Assert.Equal(4, _fileSystem.VirtualStore.Count); Assert.True(_fileSystem.VirtualStore.ContainsKey(path)); Assert.True(_fileSystem.VirtualStore.ContainsKey("AutoRest.json")); diff --git a/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs b/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs index 25465a14c18e6..94dd5ffd7b726 100644 --- a/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs +++ b/AutoRest/AutoRest.Core/ClientModel/KnownPrimaryType.cs @@ -24,6 +24,8 @@ public enum KnownPrimaryType TimeSpan, Boolean, Credentials, - Uuid + Uuid, + Base64Url, + UnixTime } } diff --git a/AutoRest/AutoRest.Core/CodeGenerator.cs b/AutoRest/AutoRest.Core/CodeGenerator.cs index 8efb1c0311361..57dbecb697346 100644 --- a/AutoRest/AutoRest.Core/CodeGenerator.cs +++ b/AutoRest/AutoRest.Core/CodeGenerator.cs @@ -16,6 +16,7 @@ namespace Microsoft.Rest.Generator public abstract class CodeGenerator { public const string EnumObject = "x-ms-enum"; + private bool firstTimeWriteSingleFile = true; protected CodeGenerator(Settings settings) { @@ -99,7 +100,7 @@ public async Task Write(ITemplate template, string fileName) /// public async Task Write(string template, string fileName) { - string relativeFilePath = null; + string filePath = null; if (Settings.OutputFileName != null) { @@ -110,17 +111,19 @@ public async Task Write(string template, string fileName) ErrorManager.ThrowErrors(); } - relativeFilePath = Settings.OutputFileName; + filePath = Path.Combine(Settings.OutputDirectory, Settings.OutputFileName); + + if (firstTimeWriteSingleFile) + { + // for SingleFileGeneration clean the file before writing only if its the first time + Settings.FileSystem.DeleteFile(filePath); + firstTimeWriteSingleFile = false; + } } else { - relativeFilePath = fileName; - } - string filePath = Path.Combine(Settings.OutputDirectory, relativeFilePath); - - // cleans file before writing unless single file - if (!(Settings.OutputFileName != null && IsSingleFileGenerationSupported)) - { + filePath = Path.Combine(Settings.OutputDirectory, fileName); + // cleans file before writing Settings.FileSystem.DeleteFile(filePath); } // Make sure the directory exist diff --git a/AutoRest/AutoRest.Core/Settings.cs b/AutoRest/AutoRest.Core/Settings.cs index a014456a63bca..df99585e02d31 100644 --- a/AutoRest/AutoRest.Core/Settings.cs +++ b/AutoRest/AutoRest.Core/Settings.cs @@ -157,6 +157,10 @@ public string Header { _header = MicrosoftApacheLicenseHeader + Environment.NewLine + DefaultCodeGenerationHeaderWithoutVersion; } + else if (value == "MICROSOFT_MIT_NO_CODEGEN") + { + _header = MicrosoftMitLicenseHeader; + } else if (value == "NONE") { _header = String.Empty; diff --git a/AutoRest/AutoRest.Core/Utilities/Extensions.cs b/AutoRest/AutoRest.Core/Utilities/Extensions.cs index 23bea5173d9db..9a18e21f1f5b4 100644 --- a/AutoRest/AutoRest.Core/Utilities/Extensions.cs +++ b/AutoRest/AutoRest.Core/Utilities/Extensions.cs @@ -244,7 +244,7 @@ public static string EscapeXmlComment(this string comment) } /// - /// Returns true is the type is a PrimaryType with KnownPrimaryType matching typeToMatch. + /// Returns true if the type is a PrimaryType with KnownPrimaryType matching typeToMatch. /// /// /// @@ -263,5 +263,54 @@ public static bool IsPrimaryType(this IType type, KnownPrimaryType typeToMatch) } return false; } + + /// + /// Returns true if the is a PrimaryType with KnownPrimaryType matching + /// or a DictionaryType with ValueType matching or a SequenceType matching + /// + /// + /// + /// + public static bool IsOrContainsPrimaryType(this IType type, KnownPrimaryType typeToMatch) + { + if (type == null) + { + return false; + } + + if (type.IsPrimaryType(typeToMatch) || + type.IsDictionaryContainingType(typeToMatch) || + type.IsSequenceContainingType(typeToMatch)) + { + return true; + } + return false; + } + + /// + /// Returns true if the is a DictionaryType with ValueType matching + /// + /// + /// + /// + public static bool IsDictionaryContainingType(this IType type, KnownPrimaryType typeToMatch) + { + DictionaryType dictionaryType = type as DictionaryType; + PrimaryType dictionaryPrimaryType = dictionaryType?.ValueType as PrimaryType; + return dictionaryPrimaryType != null && dictionaryPrimaryType.IsPrimaryType(typeToMatch); + } + + /// + /// Returns true if the is a SequenceType matching + /// + /// + /// + /// + public static bool IsSequenceContainingType(this IType type, KnownPrimaryType typeToMatch) + { + SequenceType sequenceType = type as SequenceType; + PrimaryType sequencePrimaryType = sequenceType?.ElementType as PrimaryType; + return sequencePrimaryType != null && sequencePrimaryType.IsPrimaryType(typeToMatch); + } } } \ No newline at end of file diff --git a/AutoRest/AutoRest.Core/Utilities/FileSystem.cs b/AutoRest/AutoRest.Core/Utilities/FileSystem.cs index 91b4f6c18bdd0..13fab28c4cd4c 100644 --- a/AutoRest/AutoRest.Core/Utilities/FileSystem.cs +++ b/AutoRest/AutoRest.Core/Utilities/FileSystem.cs @@ -3,6 +3,7 @@ using System.IO; using System.Net; +using System.Text; namespace Microsoft.Rest.Generator.Utilities { @@ -10,13 +11,15 @@ public class FileSystem : IFileSystem { public void WriteFile(string path, string contents) { - File.WriteAllText(path, contents); + File.WriteAllText(path, contents, Encoding.UTF8); } public string ReadFileAsText(string path) { using (var client = new WebClient()) { + client.Headers.Add("User-Agent: AutoRest"); + client.Encoding = Encoding.UTF8; return client.DownloadString(path); } } diff --git a/AutoRest/AutoRest/AutoRest.csproj b/AutoRest/AutoRest/AutoRest.csproj index 8bd5ec84e97dd..7c578e0980acb 100644 --- a/AutoRest/AutoRest/AutoRest.csproj +++ b/AutoRest/AutoRest/AutoRest.csproj @@ -31,6 +31,7 @@ Properties\AssemblyVersionInfo.cs + @@ -70,4 +71,4 @@ - + \ No newline at end of file diff --git a/AutoRest/AutoRest/ExitCode.cs b/AutoRest/AutoRest/ExitCode.cs new file mode 100644 index 0000000000000..fe09a82b44c21 --- /dev/null +++ b/AutoRest/AutoRest/ExitCode.cs @@ -0,0 +1,14 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +namespace Microsoft.Rest.Generator.Cli +{ + /// + /// Available exit codes. + /// + public enum ExitCode : int + { + Success = 0, + Error = 1 + } +} diff --git a/AutoRest/AutoRest/Program.cs b/AutoRest/AutoRest/Program.cs index b0c4aa7abea2b..f7bdf406b1066 100644 --- a/AutoRest/AutoRest/Program.cs +++ b/AutoRest/AutoRest/Program.cs @@ -12,8 +12,10 @@ namespace Microsoft.Rest.Generator.Cli { internal class Program { - private static void Main(string[] args) + private static int Main(string[] args) { + int exitCode = (int)ExitCode.Error; + try { Settings settings = null; @@ -69,6 +71,7 @@ private static void Main(string[] args) { Console.WriteLine(Resources.GenerationComplete, settings.CodeGenerator, settings.Input); + exitCode = (int)ExitCode.Success; } } @@ -91,6 +94,7 @@ private static void Main(string[] args) Console.Error.WriteLine(Resources.ConsoleErrorMessage, exception.Message); Console.Error.WriteLine(Resources.ConsoleErrorStackTrace, exception.StackTrace); } + return exitCode; } /// diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj new file mode 100644 index 0000000000000..01522ea89f2b4 --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj @@ -0,0 +1,89 @@ + + + + + + Debug + AnyCPU + {1C3B4A33-E045-4C8F-9202-1B651A686567} + Library + Properties + AutoRest.Generator.AzureResourceSchema.Tests + AutoRest.Generator.AzureResourceSchema.Tests + v4.5.2 + 512 + + + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + ..\packages\xunit.abstractions.2.0.0\lib\net35\xunit.abstractions.dll + True + + + ..\packages\xunit.assert.2.1.0\lib\dotnet\xunit.assert.dll + True + + + ..\packages\xunit.extensibility.core.2.1.0\lib\dotnet\xunit.core.dll + True + + + ..\packages\xunit.extensibility.execution.2.1.0\lib\net45\xunit.execution.desktop.dll + True + + + + + + + + PreserveNewest + + + + + {654344a5-0556-49c7-bfb3-59676d7440d3} + AutoRest.Generator.AzureResourceSchema + + + + + + This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. + + + + + \ No newline at end of file diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/Properties/AssemblyInfo.cs b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000..d8be4efbcaee3 --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("AutoRest.Generator.AzureResourceSchema.Tests")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoRest.Generator.AzureResourceSchema.Tests")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("1c3b4a33-e045-4c8f-9202-1b651a686567")] + +// 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("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config new file mode 100644 index 0000000000000..4e690e09d9def --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config @@ -0,0 +1,10 @@ + + + + + + + + + + \ No newline at end of file diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/AutoRest.Generator.AzureResourceSchema.csproj b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/AutoRest.Generator.AzureResourceSchema.csproj new file mode 100644 index 0000000000000..9afbe46b7ef40 --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/AutoRest.Generator.AzureResourceSchema.csproj @@ -0,0 +1,53 @@ + + + + + Debug + AnyCPU + {654344A5-0556-49C7-BFB3-59676D7440D3} + Library + Properties + Microsoft.Rest.Generator.AzureResourceSchema + AutoRest.Generator.AzureResourceSchema + v4.5.2 + 512 + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/Properties/AssemblyInfo.cs b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000..34f7036d5899a --- /dev/null +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +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("AutoRest.Generator.AzureResourceSchema")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("AutoRest.Generator.AzureResourceSchema")] +[assembly: AssemblyCopyright("Copyright © 2016")] +[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)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("654344a5-0556-49c7-bfb3-59676d7440d3")] + +// 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("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs index ec21cdd514493..6c254399697c3 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/AcceptanceTests.cs @@ -274,6 +274,10 @@ public void LroSadPathTests() Assert.Equal("Error from the server", exception.Body.Message); Assert.NotNull(exception.Request); Assert.NotNull(exception.Response); + exception = + Assert.Throws(() => client.LROSADs.PutNonRetry201Creating400InvalidJson(new Product { Location = "West US" })); + Assert.Null(exception.Body); + Assert.Equal("Long running operation failed with status 'BadRequest'.", exception.Message); exception = Assert.Throws( () => client.LROSADs.PutAsyncRelativeRetry400(new Product {Location = "West US"})); diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDuration/DurationOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDuration/DurationOperations.cs index 0a81d725f40a0..1bb297f05c5be 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDuration/DurationOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureBodyDuration/DurationOperations.cs @@ -262,9 +262,12 @@ internal DurationOperations(AutoRestDurationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(durationBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ArrayOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ArrayOperations.cs index 1f102b7d253f8..084e2252f5c2f 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ArrayOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ArrayOperations.cs @@ -267,9 +267,12 @@ internal ArrayOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -552,9 +555,12 @@ internal ArrayOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/AzureCompositeModel.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/AzureCompositeModel.cs index 1b85b132a8e1f..4a1b72d67ed36 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/AzureCompositeModel.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/AzureCompositeModel.cs @@ -598,9 +598,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -781,9 +784,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/BasicOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/BasicOperations.cs index 971958b5cce24..48f31b747d153 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/BasicOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/BasicOperations.cs @@ -273,9 +273,12 @@ internal BasicOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/DictionaryOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/DictionaryOperations.cs index 7bff642eb2e8e..00abbb1a9f230 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/DictionaryOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/DictionaryOperations.cs @@ -267,9 +267,12 @@ internal DictionaryOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -552,9 +555,12 @@ internal DictionaryOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/InheritanceOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/InheritanceOperations.cs index e9259e72611d0..6fc88683f2532 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/InheritanceOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/InheritanceOperations.cs @@ -270,9 +270,12 @@ internal InheritanceOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphicrecursiveOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphicrecursiveOperations.cs index 2498f6ef1f370..62c2becc51e81 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphicrecursiveOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphicrecursiveOperations.cs @@ -323,9 +323,12 @@ internal PolymorphicrecursiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphismOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphismOperations.cs index 58c94cd664148..e731fe36e914a 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphismOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PolymorphismOperations.cs @@ -304,9 +304,12 @@ internal PolymorphismOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -474,9 +477,12 @@ internal PolymorphismOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PrimitiveOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PrimitiveOperations.cs index 973c9684fdf7a..6e66f9fa38195 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PrimitiveOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/PrimitiveOperations.cs @@ -267,9 +267,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -552,9 +555,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -837,9 +843,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1123,9 +1132,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1408,9 +1420,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1693,9 +1708,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1978,9 +1996,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2263,9 +2284,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2549,9 +2573,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2831,9 +2858,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3116,9 +3146,12 @@ internal PrimitiveOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ReadonlypropertyOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ReadonlypropertyOperations.cs index 56feb12b1ce51..70e1a11d28b4b 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ReadonlypropertyOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/ReadonlypropertyOperations.cs @@ -266,9 +266,12 @@ internal ReadonlypropertyOperations(AzureCompositeModel client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureParameterGrouping/ParameterGroupingOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureParameterGrouping/ParameterGroupingOperations.cs index 9a2bf74564bac..7fe382cfcdee6 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureParameterGrouping/ParameterGroupingOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureParameterGrouping/ParameterGroupingOperations.cs @@ -161,9 +161,12 @@ internal ParameterGroupingOperations(AutoRestParameterGroupingTestService client // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureResource/AutoRestResourceFlatteningTestService.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureResource/AutoRestResourceFlatteningTestService.cs index ce1bd46bdd5d8..a922764f2b369 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureResource/AutoRestResourceFlatteningTestService.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/AzureResource/AutoRestResourceFlatteningTestService.cs @@ -347,9 +347,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceArray != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -628,9 +631,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceDictionary != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -909,9 +915,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceComplexObject != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/ILROSADsOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/ILROSADsOperations.cs index 60ac71a045d3e..5717f7f8f64e8 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/ILROSADsOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/ILROSADsOperations.cs @@ -79,6 +79,34 @@ public partial interface ILROSADsOperations /// Task> BeginPutNonRetry201Creating400WithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// Product to put + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> PutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// Product to put + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> BeginPutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// /// Long running put request, service returns a 200 with /// ProvisioningState=’Creating’. Poll the endpoint indicated in the /// Azure-AsyncOperation header for operation status diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs index 0717455b58c3c..9ed93a653fb58 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LRORetrysOperations.cs @@ -145,9 +145,12 @@ internal LRORetrysOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -349,9 +352,12 @@ internal LRORetrysOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1083,9 +1089,12 @@ internal LRORetrysOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1262,9 +1271,12 @@ internal LRORetrysOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs index bf8e7415095a3..cbd54f78112ae 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperations.cs @@ -139,9 +139,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -339,9 +342,215 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Set Credentials + if (this.Client.Credentials != null) + { + cancellationToken.ThrowIfCancellationRequested(); + await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200 && (int)_statusCode != 201) + { + var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + CloudError _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex = new CloudException(_errorBody.Message); + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new AzureOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_httpResponse.Headers.Contains("x-ms-request-id")) + { + _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); + } + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + // Deserialize Response + if ((int)_statusCode == 201) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// Product to put + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + public async Task> PutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Send Request + AzureOperationResponse _response = await BeginPutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync( + product, customHeaders, cancellationToken); + return await this.Client.GetPutOrPatchOperationResultAsync(_response, + customHeaders, + cancellationToken); + } + + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// Product to put + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> BeginPutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(Product product = default(Product), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("product", product); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "BeginPutNonRetry201Creating400InvalidJson", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "lro/nonretryerror/put/201/creating/400/invalidjson").ToString(); + List _queryParameters = new List(); + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) + { + _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); + } + if (this.Client.AcceptLanguage != null) + { + if (_httpRequest.Headers.Contains("accept-language")) + { + _httpRequest.Headers.Remove("accept-language"); + } + _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); + } + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -541,9 +750,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1225,9 +1437,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1398,9 +1613,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1575,9 +1793,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1752,9 +1973,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1954,9 +2178,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2151,9 +2378,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2663,9 +2893,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2840,9 +3073,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3017,9 +3253,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3201,9 +3440,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3398,9 +3640,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -4088,9 +4333,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -4265,9 +4513,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -4442,9 +4693,12 @@ internal LROSADsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperationsExtensions.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperationsExtensions.cs index 86b6c1b083fc9..dc7d177cbe402 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperationsExtensions.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROSADsOperationsExtensions.cs @@ -162,6 +162,78 @@ public static partial class LROSADsOperationsExtensions } } + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// The operations group for this extension method. + /// + /// + /// Product to put + /// + public static Product PutNonRetry201Creating400InvalidJson(this ILROSADsOperations operations, Product product = default(Product)) + { + return Task.Factory.StartNew(s => ((ILROSADsOperations)s).PutNonRetry201Creating400InvalidJsonAsync(product), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// The operations group for this extension method. + /// + /// + /// Product to put + /// + /// + /// The cancellation token. + /// + public static async Task PutNonRetry201Creating400InvalidJsonAsync(this ILROSADsOperations operations, Product product = default(Product), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.PutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// The operations group for this extension method. + /// + /// + /// Product to put + /// + public static Product BeginPutNonRetry201Creating400InvalidJson(this ILROSADsOperations operations, Product product = default(Product)) + { + return Task.Factory.StartNew(s => ((ILROSADsOperations)s).BeginPutNonRetry201Creating400InvalidJsonAsync(product), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Long running put request, service returns a Product with + /// 'ProvisioningState' = 'Creating' and 201 response code + /// + /// + /// The operations group for this extension method. + /// + /// + /// Product to put + /// + /// + /// The cancellation token. + /// + public static async Task BeginPutNonRetry201Creating400InvalidJsonAsync(this ILROSADsOperations operations, Product product = default(Product), CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.BeginPutNonRetry201Creating400InvalidJsonWithHttpMessagesAsync(product, null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + /// /// Long running put request, service returns a 200 with /// ProvisioningState=’Creating’. Poll the endpoint indicated in the diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsCustomHeaderOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsCustomHeaderOperations.cs index ef38e4360dffc..a6475eba268d4 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsCustomHeaderOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsCustomHeaderOperations.cs @@ -147,9 +147,12 @@ internal LROsCustomHeaderOperations(AutoRestLongRunningOperationTestService clie // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -348,9 +351,12 @@ internal LROsCustomHeaderOperations(AutoRestLongRunningOperationTestService clie // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -550,9 +556,12 @@ internal LROsCustomHeaderOperations(AutoRestLongRunningOperationTestService clie // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -731,9 +740,12 @@ internal LROsCustomHeaderOperations(AutoRestLongRunningOperationTestService clie // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsOperations.cs b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsOperations.cs index 1ff59d6881ad5..b518b2963bc7e 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsOperations.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp.Tests/Expected/AcceptanceTests/Lro/LROsOperations.cs @@ -141,9 +141,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -323,9 +326,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -507,9 +513,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -693,9 +702,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -897,9 +909,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1083,9 +1098,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1287,9 +1305,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1471,9 +1492,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1668,9 +1692,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1865,9 +1892,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2062,9 +2092,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2259,9 +2292,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2456,9 +2492,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2649,9 +2688,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(sku, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(sku != null) + { + _requestContent = SafeJsonConvert.SerializeObject(sku, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -2829,9 +2871,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(sku, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(sku != null) + { + _requestContent = SafeJsonConvert.SerializeObject(sku, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3009,9 +3054,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -3189,9 +3237,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -5698,9 +5749,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -5873,9 +5927,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -6068,9 +6125,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -6263,9 +6323,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -6458,9 +6521,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -6635,9 +6701,12 @@ internal LROsOperations(AutoRestLongRunningOperationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs b/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs index 6ec3ab05bd8c4..5c7f0b5bb3809 100644 --- a/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs +++ b/AutoRest/Generators/CSharp/Azure.CSharp/AzureCSharpCodeGenerator.cs @@ -18,7 +18,7 @@ public class AzureCSharpCodeGenerator : CSharpCodeGenerator { private readonly AzureCSharpCodeNamer _namer; - private const string ClientRuntimePackage = "Microsoft.Rest.ClientRuntime.Azure.3.1.0"; + private const string ClientRuntimePackage = "Microsoft.Rest.ClientRuntime.Azure.3.2.0"; // page extensions class dictionary. private IDictionary, string> pageClasses; diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 66b37df45fc4a..804db915e6111 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs @@ -50,6 +50,7 @@ using Fixtures.PetstoreV2; using Fixtures.AcceptanceTestsCompositeBoolIntClient; using Fixtures.AcceptanceTestsCustomBaseUri; +using Fixtures.AcceptanceTestsCustomBaseUriMoreOptions; using System.Net.Http; using Fixtures.AcceptanceTestsModelFlattening; using Fixtures.AcceptanceTestsModelFlattening.Models; @@ -197,12 +198,16 @@ public void IntegerTests() client.IntModel.PutMin32(Int32.MinValue); client.IntModel.PutMax64(Int64.MaxValue); client.IntModel.PutMin64(Int64.MinValue); + client.IntModel.PutUnixTimeDate(new DateTime(2016, 4, 13, 0, 0, 0)); client.IntModel.GetNull(); Assert.Throws(() => client.IntModel.GetInvalid()); Assert.Throws(() => client.IntModel.GetOverflowInt32()); Assert.Throws(() => client.IntModel.GetOverflowInt64()); Assert.Throws(() => client.IntModel.GetUnderflowInt32()); Assert.Throws(() => client.IntModel.GetUnderflowInt64()); + Assert.Throws(() => client.IntModel.GetInvalidUnixTime()); + Assert.Null(client.IntModel.GetNullUnixTime()); + Assert.Equal(new DateTime(2016, 4, 13, 0, 0, 0), client.IntModel.GetUnixTime()); } [Fact] @@ -275,6 +280,12 @@ public void StringTests() Assert.Null(client.StringModel.GetNotProvided()); Assert.Equal(Colors.Redcolor, client.EnumModel.GetNotExpandable()); client.EnumModel.PutNotExpandable(Colors.Redcolor); + var base64UrlEncodedString = client.StringModel.GetBase64UrlEncoded(); + var base64EncodedString = client.StringModel.GetBase64Encoded(); + Assert.Equal(Encoding.UTF8.GetString(base64UrlEncodedString), "a string that gets encoded with base64url"); + Assert.Equal(Encoding.UTF8.GetString(base64EncodedString), "a string that gets encoded with base64"); + Assert.Null(client.StringModel.GetNullBase64UrlEncoded()); + client.StringModel.PutBase64UrlEncoded(Encoding.UTF8.GetBytes("a string that gets encoded with base64url")); } } @@ -652,6 +663,11 @@ public void ArrayTests() Assert.Equal(new List { guid1, guid2, guid3 }, client.Array.GetUuidValid()); client.Array.PutUuidValid(new List { guid1, guid2, guid3 }); Assert.Throws(() => client.Array.GetUuidInvalidChars()); + + var base64Url1 = Encoding.UTF8.GetBytes("a string that gets encoded with base64url"); + var base64Url2 = Encoding.UTF8.GetBytes("test string"); + var base64Url3 = Encoding.UTF8.GetBytes("Lorem ipsum"); + Assert.Equal(new List { base64Url1, base64Url2, base64Url3 }, client.Array.GetBase64Url()); } } @@ -961,6 +977,13 @@ private static void TestDictionaryPrimitiveTypes(AutoRestSwaggerBATdictionarySer Assert.True(bytesResult.ContainsKey(key)); Assert.Equal(bytesNull[key], bytesResult[key], new ByteArrayEqualityComparer()); } + // GET prim/base64url/valid + var base64UrlString1 = Encoding.UTF8.GetBytes("a string that gets encoded with base64url"); + var base64UrlString2 = Encoding.UTF8.GetBytes("test string"); + var base64UrlString3 = Encoding.UTF8.GetBytes("Lorem ipsum"); + var base64UrlStringValid = new Dictionary {{"0", base64UrlString1}, {"1", base64UrlString2}, {"2", base64UrlString3}}; + var base64UrlStringResult = client.Dictionary.GetBase64Url(); + Assert.Equal(base64UrlStringValid, base64UrlStringResult); } private static void TestBasicDictionaryParsing(AutoRestSwaggerBATdictionaryService client) @@ -1329,6 +1352,10 @@ public void UrlPathTests() Assert.Throws(() => client.Paths.StringNull(null)); client.Paths.StringUrlEncoded(); client.Paths.EnumValid(UriColor.Greencolor); + client.Paths.Base64Url(Encoding.UTF8.GetBytes("lorem")); + var testArray = new List { "ArrayPath1", @"begin!*'();:@ &=+$,/?#[]end", null, "" }; + client.Paths.ArrayCsvInPath(testArray); + client.Paths.UnixTimeUrl(new DateTime(2016, 4, 13, 0, 0, 0)); } } @@ -1930,6 +1957,21 @@ public void CustomBaseUriTests() } } + [Fact] + public void CustomBaseUriMoreOptionsTests() + { + SwaggerSpecRunner.RunTests( + SwaggerPath("custom-baseUrl-more-options.json"), ExpectedPath("CustomBaseUriMoreOptions")); + using (var client = new AutoRestParameterizedCustomHostTestClient()) + { + client.SubscriptionId = "test12"; + // small modification to the "host" portion to include the port and the '.' + client.DnsSuffix = string.Format(CultureInfo.InvariantCulture, "{0}.:{1}", "host", Fixture.Port); + Assert.Equal(HttpStatusCode.OK, + client.Paths.GetEmptyWithHttpMessagesAsync("http://lo", "cal", "key1").Result.Response.StatusCode); + } + } + [Fact] public void CustomBaseUriNegativeTests() { @@ -2165,7 +2207,8 @@ public void ModelFlatteningSimpleTest() Description = "product description", ProductId = "123", MaxProductDisplayName = "max name", - Odatavalue = "http://foo" + Odatavalue = "http://foo", + GenericValue = "https://generic" }; var resultProduct = client.PutSimpleProduct(simpleProduct); Assert.Equal(JsonConvert.SerializeObject(resultProduct), JsonConvert.SerializeObject(simpleProduct)); @@ -2185,7 +2228,7 @@ public void ModelFlatteningWithParameterFlatteningTest() MaxProductDisplayName = "max name", Odatavalue = "http://foo" }; - var resultProduct = client.PostFlattenedSimpleProduct("123", "max name", "product description", "http://foo"); + var resultProduct = client.PostFlattenedSimpleProduct("123", "max name", "product description", null, "http://foo"); Assert.Equal(JsonConvert.SerializeObject(resultProduct), JsonConvert.SerializeObject(simpleProduct)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs index 0b9d94dc699a5..3812833eacaae 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/Array.cs @@ -459,9 +459,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -689,9 +692,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1157,9 +1163,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1625,9 +1634,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2093,9 +2105,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2561,9 +2576,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3029,9 +3047,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3501,9 +3522,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3850,9 +3874,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateJsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -4320,9 +4347,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -4790,9 +4820,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateTimeRfc1123JsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateTimeRfc1123JsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5020,9 +5053,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5252,9 +5288,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5429,6 +5468,126 @@ public Array(AutoRestSwaggerBATArrayService client) return _result; } + /// + /// Get array value ['a string that gets encoded with base64url', 'test + /// string' 'Lorem ipsum'] with the items base64url encoded + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> GetBase64UrlWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetBase64Url", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "array/prim/base64url/valid").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + /// /// Get array of complex type null value /// @@ -6082,9 +6241,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -6790,9 +6952,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -7504,9 +7669,12 @@ public Array(AutoRestSwaggerBATArrayService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/ArrayExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/ArrayExtensions.cs index 283d2324b9961..1b1f220f613eb 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/ArrayExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/ArrayExtensions.cs @@ -1344,6 +1344,36 @@ public static IList GetByteInvalidNull(this IArray operations) } } + /// + /// Get array value ['a string that gets encoded with base64url', 'test + /// string' 'Lorem ipsum'] with the items base64url encoded + /// + /// + /// The operations group for this extension method. + /// + public static IList GetBase64Url(this IArray operations) + { + return Task.Factory.StartNew(s => ((IArray)s).GetBase64UrlAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get array value ['a string that gets encoded with base64url', 'test + /// string' 'Lorem ipsum'] with the items base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> GetBase64UrlAsync(this IArray operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetBase64UrlWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + /// /// Get array of complex type null value /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/IArray.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/IArray.cs index 51288d0a84660..65f46721b9268 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/IArray.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyArray/IArray.cs @@ -520,6 +520,17 @@ public partial interface IArray /// Task>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// + /// Get array value ['a string that gets encoded with base64url', + /// 'test string' 'Lorem ipsum'] with the items base64url encoded + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> GetBase64UrlWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// /// Get array of complex type null value /// /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyBoolean/BoolModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyBoolean/BoolModel.cs index d287e6188c543..d78403311ec8c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyBoolean/BoolModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyBoolean/BoolModel.cs @@ -217,9 +217,12 @@ public BoolModel(AutoRestBoolTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(boolBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -443,9 +446,12 @@ public BoolModel(AutoRestBoolTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(boolBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyByte/ByteModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyByte/ByteModel.cs index 6faca5d0f82c5..6343dc98de5e5 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyByte/ByteModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyByte/ByteModel.cs @@ -460,9 +460,12 @@ public ByteModel(AutoRestSwaggerBATByteService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(byteBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(byteBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(byteBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Array.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Array.cs index f24a2d97284af..5009f9e28bcea 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Array.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Array.cs @@ -222,9 +222,12 @@ public Array(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -453,9 +456,12 @@ public Array(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/BasicOperations.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/BasicOperations.cs index a9dd0b484a555..39cc806a8c839 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/BasicOperations.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/BasicOperations.cs @@ -231,9 +231,12 @@ public BasicOperations(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Dictionary.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Dictionary.cs index 03d740e5eae86..d707e2106fd98 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Dictionary.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Dictionary.cs @@ -222,9 +222,12 @@ public Dictionary(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -453,9 +456,12 @@ public Dictionary(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Inheritance.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Inheritance.cs index d8b687fe82965..8884055cd84c5 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Inheritance.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Inheritance.cs @@ -225,9 +225,12 @@ public Inheritance(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphicrecursive.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphicrecursive.cs index 8a4753fa788be..9e3d47fc4a98a 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphicrecursive.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphicrecursive.cs @@ -278,9 +278,12 @@ public Polymorphicrecursive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphism.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphism.cs index 62d9e5af2d7c7..e9f32ec1faccf 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphism.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Polymorphism.cs @@ -259,9 +259,12 @@ public Polymorphism(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -402,9 +405,12 @@ public Polymorphism(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Primitive.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Primitive.cs index caed868d0e270..334e0f205ddcf 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Primitive.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Primitive.cs @@ -222,9 +222,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -453,9 +456,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -684,9 +690,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -916,9 +925,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1147,9 +1159,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1378,9 +1393,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1609,9 +1627,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1840,9 +1861,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2072,9 +2096,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2300,9 +2327,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2531,9 +2561,12 @@ public Primitive(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Readonlyproperty.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Readonlyproperty.cs index 15758e93c2836..57471567ee6da 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Readonlyproperty.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyComplex/Readonlyproperty.cs @@ -221,9 +221,12 @@ public Readonlyproperty(AutoRestComplexTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(complexBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDate/Date.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDate/Date.cs index 509781fe382c5..0a4c07170740d 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDate/Date.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDate/Date.cs @@ -574,9 +574,12 @@ public Date(AutoRestDateTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(dateBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -800,9 +803,12 @@ public Date(AutoRestDateTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(dateBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(dateBody, new DateJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTime/Datetime.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTime/Datetime.cs index a46a03a8ae9b4..2248d4263b000 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTime/Datetime.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTime/Datetime.cs @@ -574,9 +574,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -920,9 +923,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1268,9 +1274,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1615,9 +1624,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1841,9 +1853,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2067,9 +2082,12 @@ public Datetime(AutoRestDateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/Datetimerfc1123.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/Datetimerfc1123.cs index 2506c533d5633..068aced56df75 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/Datetimerfc1123.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/Datetimerfc1123.cs @@ -574,9 +574,12 @@ public Datetimerfc1123(AutoRestRFC1123DateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -919,9 +922,12 @@ public Datetimerfc1123(AutoRestRFC1123DateTimeTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(datetimeBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(datetimeBody, new DateTimeRfc1123JsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs index a370279790948..ec2b9dd872bd3 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/Dictionary.cs @@ -340,9 +340,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1047,9 +1050,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1515,9 +1521,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1983,9 +1992,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2451,9 +2463,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2919,9 +2934,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3387,9 +3405,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -3857,9 +3878,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateJsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -4327,9 +4351,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -4798,9 +4825,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateTimeRfc1123JsonConverter()); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, new DateTimeRfc1123JsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5029,9 +5059,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5261,9 +5294,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -5438,6 +5474,126 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) return _result; } + /// + /// Get base64url dictionary value {"0": "a string that gets encoded with + /// base64url", "1": "test string", "2": "Lorem ipsum"} + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task>> GetBase64UrlWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetBase64Url", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "dictionary/prim/base64url/valid").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse>(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject>(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + /// /// Get dictionary of complex type null value /// @@ -6092,9 +6248,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -6802,9 +6961,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -7517,9 +7679,12 @@ public Dictionary(AutoRestSwaggerBATdictionaryService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(arrayBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(arrayBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/DictionaryExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/DictionaryExtensions.cs index 890eea653ece8..081c30c09bcb2 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/DictionaryExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/DictionaryExtensions.cs @@ -1345,6 +1345,36 @@ public static IDictionary GetByteInvalidNull(this IDictionary op } } + /// + /// Get base64url dictionary value {"0": "a string that gets encoded with + /// base64url", "1": "test string", "2": "Lorem ipsum"} + /// + /// + /// The operations group for this extension method. + /// + public static IDictionary GetBase64Url(this IDictionary operations) + { + return Task.Factory.StartNew(s => ((IDictionary)s).GetBase64UrlAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get base64url dictionary value {"0": "a string that gets encoded with + /// base64url", "1": "test string", "2": "Lorem ipsum"} + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task> GetBase64UrlAsync(this IDictionary operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetBase64UrlWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + /// /// Get dictionary of complex type null value /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/IDictionary.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/IDictionary.cs index 53da3621b1eb1..8c5451a26f103 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/IDictionary.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDictionary/IDictionary.cs @@ -524,6 +524,17 @@ public partial interface IDictionary /// Task>> GetByteInvalidNullWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// + /// Get base64url dictionary value {"0": "a string that gets encoded + /// with base64url", "1": "test string", "2": "Lorem ipsum"} + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task>> GetBase64UrlWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// /// Get dictionary of complex type null value /// /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDuration/Duration.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDuration/Duration.cs index 7893ed1ee8506..42b50edf64d33 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDuration/Duration.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyDuration/Duration.cs @@ -217,9 +217,12 @@ public Duration(AutoRestDurationTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(durationBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(durationBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IIntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IIntModel.cs index 4b90323fef26b..7131504bb1855 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IIntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IIntModel.cs @@ -129,5 +129,47 @@ public partial interface IIntModel /// The cancellation token. /// Task PutMin64WithHttpMessagesAsync(long intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Put datetime encoded as Unix time + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task PutUnixTimeDateWithHttpMessagesAsync(DateTime intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get invalid Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get null Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetNullUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs index 7c65575d05ed7..9c9b57ebbb2a4 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModel.cs @@ -812,9 +812,12 @@ public IntModel(AutoRestIntegerTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -919,9 +922,12 @@ public IntModel(AutoRestIntegerTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1026,9 +1032,12 @@ public IntModel(AutoRestIntegerTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1133,9 +1142,12 @@ public IntModel(AutoRestIntegerTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1190,5 +1202,472 @@ public IntModel(AutoRestIntegerTestService client) return _result; } + /// + /// Get datetime encoded as Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task PutUnixTimeDateWithHttpMessagesAsync(DateTime intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("intBody", intBody); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PutUnixTimeDate", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, new UnixTimeJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get invalid Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetInvalidUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalidunixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get null Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetNullUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetNullUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/nullunixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModelExtensions.cs index 0c57e20b0aade..c0bc0812ebde8 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyInteger/IntModelExtensions.cs @@ -305,5 +305,118 @@ public static void PutMin64(this IIntModel operations, long intBody) await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// The operations group for this extension method. + /// + /// + /// + public static void PutUnixTimeDate(this IIntModel operations, DateTime intBody) + { + Task.Factory.StartNew(s => ((IIntModel)s).PutUnixTimeDateAsync(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task PutUnixTimeDateAsync(this IIntModel operations, DateTime intBody, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.PutUnixTimeDateWithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get invalid Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetInvalidUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get invalid Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetInvalidUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetInvalidUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get null Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetNullUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetNullUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get null Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetNullUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetNullUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyNumber/Number.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyNumber/Number.cs index dc98d33d86449..4b60b5582025a 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyNumber/Number.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyNumber/Number.cs @@ -574,9 +574,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -800,9 +803,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1026,9 +1032,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1252,9 +1261,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1478,9 +1490,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1704,9 +1719,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1930,9 +1948,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2156,9 +2177,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2382,9 +2406,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2608,9 +2635,12 @@ public Number(AutoRestNumberTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(numberBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(numberBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/EnumModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/EnumModel.cs index c1701bfb31ad1..8861a350c04b9 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/EnumModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/EnumModel.cs @@ -220,9 +220,12 @@ public EnumModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs index ead7a87735a93..e1823d0463b87 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/IStringModel.cs @@ -136,5 +136,47 @@ public partial interface IStringModel /// The cancellation token. /// Task> GetNotProvidedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get value that is base64 encoded + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetBase64EncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get value that is base64url encoded + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetBase64UrlEncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Put value that is base64url encoded + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task PutBase64UrlEncodedWithHttpMessagesAsync(byte[] stringBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get null value that is expected to be base64url encoded + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetNullBase64UrlEncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs index 61557a3917295..e32308ac6f570 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModel.cs @@ -218,9 +218,12 @@ public StringModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -449,9 +452,12 @@ public StringModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -683,9 +689,12 @@ public StringModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -919,9 +928,12 @@ public StringModel(AutoRestSwaggerBATService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1095,5 +1107,476 @@ public StringModel(AutoRestSwaggerBATService client) return _result; } + /// + /// Get value that is base64 encoded + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetBase64EncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetBase64Encoded", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/base64Encoding").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get value that is base64url encoded + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetBase64UrlEncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetBase64UrlEncoded", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/base64UrlEncoding").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Put value that is base64url encoded + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task PutBase64UrlEncodedWithHttpMessagesAsync(byte[] stringBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (stringBody == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "stringBody"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("stringBody", stringBody); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PutBase64UrlEncoded", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/base64UrlEncoding").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(stringBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(stringBody, new Base64UrlJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get null value that is expected to be base64url encoded + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetNullBase64UrlEncodedWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetNullBase64UrlEncoded", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/nullBase64UrlEncoding").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new Base64UrlJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs index aaa2faa66b405..7e028f2034390 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/BodyString/StringModelExtensions.cs @@ -301,5 +301,118 @@ public static string GetNotProvided(this IStringModel operations) } } + /// + /// Get value that is base64 encoded + /// + /// + /// The operations group for this extension method. + /// + public static byte[] GetBase64Encoded(this IStringModel operations) + { + return Task.Factory.StartNew(s => ((IStringModel)s).GetBase64EncodedAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get value that is base64 encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetBase64EncodedAsync(this IStringModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetBase64EncodedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get value that is base64url encoded + /// + /// + /// The operations group for this extension method. + /// + public static byte[] GetBase64UrlEncoded(this IStringModel operations) + { + return Task.Factory.StartNew(s => ((IStringModel)s).GetBase64UrlEncodedAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get value that is base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetBase64UrlEncodedAsync(this IStringModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetBase64UrlEncodedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Put value that is base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// + public static void PutBase64UrlEncoded(this IStringModel operations, byte[] stringBody) + { + Task.Factory.StartNew(s => ((IStringModel)s).PutBase64UrlEncodedAsync(stringBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Put value that is base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task PutBase64UrlEncodedAsync(this IStringModel operations, byte[] stringBody, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.PutBase64UrlEncodedWithHttpMessagesAsync(stringBody, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get null value that is expected to be base64url encoded + /// + /// + /// The operations group for this extension method. + /// + public static byte[] GetNullBase64UrlEncoded(this IStringModel operations) + { + return Task.Factory.StartNew(s => ((IStringModel)s).GetNullBase64UrlEncodedAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get null value that is expected to be base64url encoded + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetNullBase64UrlEncodedAsync(this IStringModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetNullBase64UrlEncodedWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/BoolModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/BoolModel.cs index 9c761510fc304..22ff99e128385 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/BoolModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/BoolModel.cs @@ -217,9 +217,12 @@ public BoolModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(boolBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -443,9 +446,12 @@ public BoolModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(boolBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(boolBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IIntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IIntModel.cs index 4917e355224d7..d0b518478669c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IIntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IIntModel.cs @@ -129,5 +129,47 @@ public partial interface IIntModel /// The cancellation token. /// Task PutMin64WithHttpMessagesAsync(long intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Put datetime encoded as Unix time + /// + /// + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task PutUnixTimeDateWithHttpMessagesAsync(DateTime intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get invalid Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get null Unix time value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task> GetNullUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs index 6932d90778be5..2047fd860871e 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModel.cs @@ -812,9 +812,12 @@ public IntModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -919,9 +922,12 @@ public IntModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1026,9 +1032,12 @@ public IntModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1133,9 +1142,12 @@ public IntModel(CompositeBoolInt client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1190,5 +1202,472 @@ public IntModel(CompositeBoolInt client) return _result; } + /// + /// Get datetime encoded as Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task PutUnixTimeDateWithHttpMessagesAsync(DateTime intBody, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("intBody", intBody); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "PutUnixTimeDate", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/unixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("PUT"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + if(intBody != null) + { + _requestContent = SafeJsonConvert.SerializeObject(intBody, new UnixTimeJsonConverter()); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get invalid Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetInvalidUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetInvalidUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/invalidunixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get null Unix time value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task> GetNullUnixTimeWithHttpMessagesAsync(Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetNullUnixTime", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "int/nullunixtime").ToString(); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + // Deserialize Response + if ((int)_statusCode == 200) + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + try + { + _result.Body = SafeJsonConvert.DeserializeObject(_responseContent, new UnixTimeJsonConverter()); + } + catch (JsonException ex) + { + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); + } + } + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModelExtensions.cs index a203d3cee39e7..009277ea5077b 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/IntModelExtensions.cs @@ -305,5 +305,118 @@ public static void PutMin64(this IIntModel operations, long intBody) await operations.PutMin64WithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); } + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get datetime encoded as Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// The operations group for this extension method. + /// + /// + /// + public static void PutUnixTimeDate(this IIntModel operations, DateTime intBody) + { + Task.Factory.StartNew(s => ((IIntModel)s).PutUnixTimeDateAsync(intBody), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Put datetime encoded as Unix time + /// + /// + /// The operations group for this extension method. + /// + /// + /// + /// + /// The cancellation token. + /// + public static async Task PutUnixTimeDateAsync(this IIntModel operations, DateTime intBody, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.PutUnixTimeDateWithHttpMessagesAsync(intBody, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get invalid Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetInvalidUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetInvalidUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get invalid Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetInvalidUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetInvalidUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + + /// + /// Get null Unix time value + /// + /// + /// The operations group for this extension method. + /// + public static DateTime? GetNullUnixTime(this IIntModel operations) + { + return Task.Factory.StartNew(s => ((IIntModel)s).GetNullUnixTimeAsync(), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get null Unix time value + /// + /// + /// The operations group for this extension method. + /// + /// + /// The cancellation token. + /// + public static async Task GetNullUnixTimeAsync(this IIntModel operations, CancellationToken cancellationToken = default(CancellationToken)) + { + using (var _result = await operations.GetNullUnixTimeWithHttpMessagesAsync(null, cancellationToken).ConfigureAwait(false)) + { + return _result.Body; + } + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/AutoRestParameterizedCustomHostTestClient.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/AutoRestParameterizedCustomHostTestClient.cs new file mode 100644 index 0000000000000..e680cbe6a8731 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/AutoRestParameterizedCustomHostTestClient.cs @@ -0,0 +1,128 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Diagnostics; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using Models; + + /// + /// Test Infrastructure for AutoRest + /// + public partial class AutoRestParameterizedCustomHostTestClient : ServiceClient, IAutoRestParameterizedCustomHostTestClient + { + /// + /// The base URI of the service. + /// + internal string BaseUri {get; set;} + + /// + /// Gets or sets json serialization settings. + /// + public JsonSerializerSettings SerializationSettings { get; private set; } + + /// + /// Gets or sets json deserialization settings. + /// + public JsonSerializerSettings DeserializationSettings { get; private set; } + + /// + /// The subscription id with value 'test12'. + /// + public string SubscriptionId { get; set; } + + /// + /// A string value that is used as a global part of the parameterized host. + /// Default value 'host'. + /// + public string DnsSuffix { get; set; } + + /// + /// Gets the IPaths. + /// + public virtual IPaths Paths { get; private set; } + + /// + /// Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestParameterizedCustomHostTestClient(params DelegatingHandler[] handlers) : base(handlers) + { + this.Initialize(); + } + + /// + /// Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + /// + /// + /// Optional. The http client handler used to handle http transport. + /// + /// + /// Optional. The delegating handlers to add to the http client pipeline. + /// + public AutoRestParameterizedCustomHostTestClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) + { + this.Initialize(); + } + + /// + /// An optional partial-method to perform custom initialization. + /// + partial void CustomInitialize(); + /// + /// Initializes client properties. + /// + private void Initialize() + { + this.Paths = new Paths(this); + this.BaseUri = "{vault}{secret}{dnsSuffix}"; + this.DnsSuffix = "host"; + SerializationSettings = new JsonSerializerSettings + { + Formatting = Formatting.Indented, + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + DeserializationSettings = new JsonSerializerSettings + { + DateFormatHandling = DateFormatHandling.IsoDateFormat, + DateTimeZoneHandling = DateTimeZoneHandling.Utc, + NullValueHandling = NullValueHandling.Ignore, + ReferenceLoopHandling = ReferenceLoopHandling.Serialize, + ContractResolver = new ReadOnlyJsonContractResolver(), + Converters = new List + { + new Iso8601TimeSpanConverter() + } + }; + CustomInitialize(); + } + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IAutoRestParameterizedCustomHostTestClient.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IAutoRestParameterizedCustomHostTestClient.cs new file mode 100644 index 0000000000000..87db999d81c42 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IAutoRestParameterizedCustomHostTestClient.cs @@ -0,0 +1,57 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Newtonsoft.Json; + using Microsoft.Rest; + using Models; + + /// + /// Test Infrastructure for AutoRest + /// + public partial interface IAutoRestParameterizedCustomHostTestClient : IDisposable + { + /// + /// The base URI of the service. + /// + + /// + /// Gets or sets json serialization settings. + /// + JsonSerializerSettings SerializationSettings { get; } + + /// + /// Gets or sets json deserialization settings. + /// + JsonSerializerSettings DeserializationSettings { get; } + + /// + /// The subscription id with value 'test12'. + /// + string SubscriptionId { get; set; } + + /// + /// A string value that is used as a global part of the parameterized + /// host. Default value 'host'. + /// + string DnsSuffix { get; set; } + + + /// + /// Gets the IPaths. + /// + IPaths Paths { get; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IPaths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IPaths.cs new file mode 100644 index 0000000000000..a117b914e7526 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IPaths.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Collections.Generic; + using System.Net.Http; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Models; + + /// + /// Paths operations. + /// + public partial interface IPaths + { + /// + /// Get a 200 to test a valid base uri + /// + /// + /// The vault name, e.g. https://myvault + /// + /// + /// Secret value. + /// + /// + /// The key name with value 'key1'. + /// + /// + /// The key version. Default value 'v1'. + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task GetEmptyWithHttpMessagesAsync(string vault, string secret, string keyName, string keyVersion = "v1", Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/Error.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/Error.cs new file mode 100644 index 0000000000000..82a4873e61389 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/Error.cs @@ -0,0 +1,45 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + public partial class Error + { + /// + /// Initializes a new instance of the Error class. + /// + public Error() { } + + /// + /// Initializes a new instance of the Error class. + /// + public Error(int? status = default(int?), string message = default(string)) + { + Status = status; + Message = message; + } + + /// + /// + [JsonProperty(PropertyName = "status")] + public int? Status { get; set; } + + /// + /// + [JsonProperty(PropertyName = "message")] + public string Message { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/ErrorException.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/ErrorException.cs new file mode 100644 index 0000000000000..e3ab1c0a08abc --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/ErrorException.cs @@ -0,0 +1,99 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions.Models +{ + using Microsoft.Rest; + using System; + using System.Net.Http; + using System.Runtime.Serialization; +#if !PORTABLE && !DNXCORE50 + using System.Security.Permissions; +#endif + + /// + /// Exception thrown for an invalid response with Error information. + /// +#if !PORTABLE && !DNXCORE50 + [Serializable] +#endif + public class ErrorException : RestException + { + /// + /// Gets information about the associated HTTP request. + /// + public HttpRequestMessageWrapper Request { get; set; } + + /// + /// Gets information about the associated HTTP response. + /// + public HttpResponseMessageWrapper Response { get; set; } + + /// + /// Gets or sets the body object. + /// + public Error Body { get; set; } + + /// + /// Initializes a new instance of the ErrorException class. + /// + public ErrorException() + { + } + + /// + /// Initializes a new instance of the ErrorException class. + /// + /// The exception message. + public ErrorException(string message) + : this(message, null) + { + } + + /// + /// Initializes a new instance of the ErrorException class. + /// + /// The exception message. + /// Inner exception. + public ErrorException(string message, Exception innerException) + : base(message, innerException) + { + } + +#if !PORTABLE && !DNXCORE50 + /// + /// Initializes a new instance of the ErrorException class. + /// + /// Serialization info. + /// Streaming context. + protected ErrorException(SerializationInfo info, StreamingContext context) + : base(info, context) + { + } + + /// + /// Serializes content of the exception. + /// + /// Serialization info. + /// Streaming context. + [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)] + public override void GetObjectData(SerializationInfo info, StreamingContext context) + { + base.GetObjectData(info, context); + if (info == null) + { + throw new ArgumentNullException("info"); + } + + info.AddValue("Request", Request); + info.AddValue("Response", Response); + info.AddValue("Body", Body); + } +#endif + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Paths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Paths.cs new file mode 100644 index 0000000000000..a8599cf083382 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Paths.cs @@ -0,0 +1,203 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Net; + using System.Net.Http; + using System.Net.Http.Headers; + using System.Text; + using System.Text.RegularExpressions; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + using Newtonsoft.Json; + using Models; + + /// + /// Paths operations. + /// + public partial class Paths : IServiceOperations, IPaths + { + /// + /// Initializes a new instance of the Paths class. + /// + /// + /// Reference to the service client. + /// + public Paths(AutoRestParameterizedCustomHostTestClient client) + { + if (client == null) + { + throw new ArgumentNullException("client"); + } + this.Client = client; + } + + /// + /// Gets a reference to the AutoRestParameterizedCustomHostTestClient + /// + public AutoRestParameterizedCustomHostTestClient Client { get; private set; } + + /// + /// Get a 200 to test a valid base uri + /// + /// + /// The vault name, e.g. https://myvault + /// + /// + /// Secret value. + /// + /// + /// The key name with value 'key1'. + /// + /// + /// The key version. Default value 'v1'. + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task GetEmptyWithHttpMessagesAsync(string vault, string secret, string keyName, string keyVersion = "v1", Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (vault == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "vault"); + } + if (secret == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "secret"); + } + if (this.Client.DnsSuffix == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.DnsSuffix"); + } + if (keyName == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "keyName"); + } + if (this.Client.SubscriptionId == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("vault", vault); + tracingParameters.Add("secret", secret); + tracingParameters.Add("keyName", keyName); + tracingParameters.Add("keyVersion", keyVersion); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "GetEmpty", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri; + var _url = _baseUrl + (_baseUrl.EndsWith("/") ? "" : "/") + "customuri/{subscriptionId}/{keyName}"; + _url = _url.Replace("{vault}", vault); + _url = _url.Replace("{secret}", secret); + _url = _url.Replace("{dnsSuffix}", this.Client.DnsSuffix); + _url = _url.Replace("{keyName}", Uri.EscapeDataString(keyName)); + _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); + List _queryParameters = new List(); + if (keyVersion != null) + { + _queryParameters.Add(string.Format("keyVersion={0}", Uri.EscapeDataString(keyVersion))); + } + if (_queryParameters.Count > 0) + { + _url += "?" + string.Join("&", _queryParameters); + } + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/PathsExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/PathsExtensions.cs new file mode 100644 index 0000000000000..c553414304ed0 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/PathsExtensions.cs @@ -0,0 +1,74 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsCustomBaseUriMoreOptions +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Threading; + using System.Threading.Tasks; + using Microsoft.Rest; + using Models; + + /// + /// Extension methods for Paths. + /// + public static partial class PathsExtensions + { + /// + /// Get a 200 to test a valid base uri + /// + /// + /// The operations group for this extension method. + /// + /// + /// The vault name, e.g. https://myvault + /// + /// + /// Secret value. + /// + /// + /// The key name with value 'key1'. + /// + /// + /// The key version. Default value 'v1'. + /// + public static void GetEmpty(this IPaths operations, string vault, string secret, string keyName, string keyVersion = "v1") + { + Task.Factory.StartNew(s => ((IPaths)s).GetEmptyAsync(vault, secret, keyName, keyVersion), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get a 200 to test a valid base uri + /// + /// + /// The operations group for this extension method. + /// + /// + /// The vault name, e.g. https://myvault + /// + /// + /// Secret value. + /// + /// + /// The key name with value 'key1'. + /// + /// + /// The key version. Default value 'v1'. + /// + /// + /// The cancellation token. + /// + public static async Task GetEmptyAsync(this IPaths operations, string vault, string secret, string keyName, string keyVersion = "v1", CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.GetEmptyWithHttpMessagesAsync(vault, secret, keyName, keyVersion, null, cancellationToken).ConfigureAwait(false); + } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpClientFailure.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpClientFailure.cs index 60a652f2efb7e..3df1107bea40c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpClientFailure.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpClientFailure.cs @@ -329,9 +329,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -451,9 +454,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -573,9 +579,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -695,9 +704,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1162,9 +1174,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1284,9 +1299,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1406,9 +1424,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1528,9 +1549,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1650,9 +1674,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2117,9 +2144,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2239,9 +2269,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2361,9 +2394,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2598,9 +2634,12 @@ public HttpClientFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRedirects.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRedirects.cs index 7759c53c1e4d5..01747fbf1dd29 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRedirects.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRedirects.cs @@ -575,9 +575,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -926,9 +929,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1049,9 +1055,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1398,9 +1407,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1519,9 +1531,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1640,9 +1655,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1761,9 +1779,12 @@ public HttpRedirects(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRetry.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRetry.cs index ac964e2f0c42b..6fe19ef0d1e25 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRetry.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpRetry.cs @@ -200,9 +200,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -308,9 +311,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -517,9 +523,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -625,9 +634,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -733,9 +745,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -841,9 +856,12 @@ public HttpRetry(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpServerFailure.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpServerFailure.cs index a26c0148f8ec9..425c90bf3f141 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpServerFailure.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpServerFailure.cs @@ -329,9 +329,12 @@ public HttpServerFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -451,9 +454,12 @@ public HttpServerFailure(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpSuccess.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpSuccess.cs index 550bfeb440a1e..9cef952542266 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpSuccess.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Http/HttpSuccess.cs @@ -319,9 +319,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -427,9 +430,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -535,9 +541,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -643,9 +652,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -751,9 +763,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -859,9 +874,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -967,9 +985,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1075,9 +1096,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1183,9 +1207,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1291,9 +1318,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1500,9 +1530,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1608,9 +1641,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1716,9 +1752,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1824,9 +1863,12 @@ public HttpSuccess(AutoRestHttpInfrastructureTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(booleanValue != null) + { + _requestContent = SafeJsonConvert.SerializeObject(booleanValue, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs index 111c67ef2ea6f..507c54acd120f 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestService.cs @@ -198,9 +198,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceArray != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceArray, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -425,9 +428,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceDictionary != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceDictionary, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -652,9 +658,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(resourceComplexObject != null) + { + _requestContent = SafeJsonConvert.SerializeObject(resourceComplexObject, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -883,9 +892,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(simpleBodyProduct != null) + { + _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -972,6 +984,9 @@ private void Initialize() /// /// Description of product. /// + /// + /// Generic URL value. + /// /// /// URL value. /// @@ -984,7 +999,7 @@ private void Initialize() /// /// A response object containing the response body and response headers. /// - public async Task> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + public async Task> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (productId == null) { @@ -995,12 +1010,13 @@ private void Initialize() throw new ValidationException(ValidationRules.CannotBeNull, "maxProductDisplayName"); } SimpleProduct simpleBodyProduct = default(SimpleProduct); - if (productId != null || description != null || maxProductDisplayName != null || odatavalue != null) + if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; + simpleBodyProduct.GenericValue = genericValue; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing @@ -1037,9 +1053,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(simpleBodyProduct != null) + { + _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1157,18 +1176,24 @@ private void Initialize() { maxProductDisplayName = flattenParameterGroup.MaxProductDisplayName; } + string genericValue = default(string); + if (flattenParameterGroup != null) + { + genericValue = flattenParameterGroup.GenericValue; + } string odatavalue = default(string); if (flattenParameterGroup != null) { odatavalue = flattenParameterGroup.Odatavalue; } SimpleProduct simpleBodyProduct = default(SimpleProduct); - if (productId != null || description != null || maxProductDisplayName != null || odatavalue != null) + if (productId != null || description != null || maxProductDisplayName != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.ProductId = productId; simpleBodyProduct.Description = description; simpleBodyProduct.MaxProductDisplayName = maxProductDisplayName; + simpleBodyProduct.GenericValue = genericValue; simpleBodyProduct.Odatavalue = odatavalue; } // Tracing @@ -1182,6 +1207,7 @@ private void Initialize() tracingParameters.Add("productId", productId); tracingParameters.Add("description", description); tracingParameters.Add("maxProductDisplayName", maxProductDisplayName); + tracingParameters.Add("genericValue", genericValue); tracingParameters.Add("odatavalue", odatavalue); tracingParameters.Add("simpleBodyProduct", simpleBodyProduct); tracingParameters.Add("cancellationToken", cancellationToken); @@ -1211,9 +1237,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(simpleBodyProduct != null) + { + _requestContent = SafeJsonConvert.SerializeObject(simpleBodyProduct, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestServiceExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestServiceExtensions.cs index 89debcadba39f..d2ab8e3efe09e 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestServiceExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/AutoRestResourceFlatteningTestServiceExtensions.cs @@ -249,12 +249,15 @@ public static ResourceCollection GetResourceCollection(this IAutoRestResourceFla /// /// Description of product. /// + /// + /// Generic URL value. + /// /// /// URL value. /// - public static SimpleProduct PostFlattenedSimpleProduct(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string)) + public static SimpleProduct PostFlattenedSimpleProduct(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string)) { - return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PostFlattenedSimpleProductAsync(productId, maxProductDisplayName, description, odatavalue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + return Task.Factory.StartNew(s => ((IAutoRestResourceFlatteningTestService)s).PostFlattenedSimpleProductAsync(productId, maxProductDisplayName, description, genericValue, odatavalue), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// @@ -274,15 +277,18 @@ public static ResourceCollection GetResourceCollection(this IAutoRestResourceFla /// /// Description of product. /// + /// + /// Generic URL value. + /// /// /// URL value. /// /// /// The cancellation token. /// - public static async Task PostFlattenedSimpleProductAsync(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string), CancellationToken cancellationToken = default(CancellationToken)) + public static async Task PostFlattenedSimpleProductAsync(this IAutoRestResourceFlatteningTestService operations, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), CancellationToken cancellationToken = default(CancellationToken)) { - using (var _result = await operations.PostFlattenedSimpleProductWithHttpMessagesAsync(productId, maxProductDisplayName, description, odatavalue, null, cancellationToken).ConfigureAwait(false)) + using (var _result = await operations.PostFlattenedSimpleProductWithHttpMessagesAsync(productId, maxProductDisplayName, description, genericValue, odatavalue, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/IAutoRestResourceFlatteningTestService.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/IAutoRestResourceFlatteningTestService.cs index c2b0e8724c57e..e7cdeadf98fdc 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/IAutoRestResourceFlatteningTestService.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/IAutoRestResourceFlatteningTestService.cs @@ -142,6 +142,9 @@ public partial interface IAutoRestResourceFlatteningTestService : IDisposable /// /// Description of product. /// + /// + /// Generic URL value. + /// /// /// URL value. /// @@ -151,7 +154,7 @@ public partial interface IAutoRestResourceFlatteningTestService : IDisposable /// /// The cancellation token. /// - Task> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + Task> PostFlattenedSimpleProductWithHttpMessagesAsync(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string), Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// /// Put Simple Product with client flattening true on the model diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/FlattenParameterGroup.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/FlattenParameterGroup.cs index 315e5db4ea53f..db9785813c55c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/FlattenParameterGroup.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/FlattenParameterGroup.cs @@ -29,12 +29,13 @@ public FlattenParameterGroup() { } /// /// Initializes a new instance of the FlattenParameterGroup class. /// - public FlattenParameterGroup(string name, string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string)) + public FlattenParameterGroup(string name, string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string)) { Name = name; ProductId = productId; Description = description; MaxProductDisplayName = maxProductDisplayName; + GenericValue = genericValue; Odatavalue = odatavalue; } @@ -64,6 +65,12 @@ public FlattenParameterGroup() { } [JsonProperty(PropertyName = "")] public string MaxProductDisplayName { get; set; } + /// + /// Generic URL value. + /// + [JsonProperty(PropertyName = "")] + public string GenericValue { get; set; } + /// /// URL value. /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/GenericUrl.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/GenericUrl.cs new file mode 100644 index 0000000000000..309028eb12669 --- /dev/null +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/GenericUrl.cs @@ -0,0 +1,43 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +namespace Fixtures.AcceptanceTestsModelFlattening.Models +{ + using System; + using System.Linq; + using System.Collections.Generic; + using Newtonsoft.Json; + using Microsoft.Rest; + using Microsoft.Rest.Serialization; + + /// + /// The Generic URL. + /// + public partial class GenericUrl + { + /// + /// Initializes a new instance of the GenericUrl class. + /// + public GenericUrl() { } + + /// + /// Initializes a new instance of the GenericUrl class. + /// + public GenericUrl(string genericValue = default(string)) + { + GenericValue = genericValue; + } + + /// + /// Generic URL value. + /// + [JsonProperty(PropertyName = "generic_value")] + public string GenericValue { get; set; } + + } +} diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/SimpleProduct.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/SimpleProduct.cs index 4c69296ee9335..5ee2fa897a5ea 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/SimpleProduct.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ModelFlattening/Models/SimpleProduct.cs @@ -29,10 +29,11 @@ public SimpleProduct() { } /// /// Initializes a new instance of the SimpleProduct class. /// - public SimpleProduct(string productId, string maxProductDisplayName, string description = default(string), string odatavalue = default(string)) + public SimpleProduct(string productId, string maxProductDisplayName, string description = default(string), string genericValue = default(string), string odatavalue = default(string)) : base(productId, description) { MaxProductDisplayName = maxProductDisplayName; + GenericValue = genericValue; Odatavalue = odatavalue; } /// @@ -49,6 +50,12 @@ static SimpleProduct() [JsonProperty(PropertyName = "details.max_product_display_name")] public string MaxProductDisplayName { get; set; } + /// + /// Generic URL value. + /// + [JsonProperty(PropertyName = "details.max_product_image.generic_value")] + public string GenericValue { get; set; } + /// /// URL value. /// diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ParameterFlattening/AvailabilitySets.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ParameterFlattening/AvailabilitySets.cs index a2ff4eb31d0f1..119563378110a 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ParameterFlattening/AvailabilitySets.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/ParameterFlattening/AvailabilitySets.cs @@ -132,9 +132,12 @@ public AvailabilitySets(AutoRestParameterFlattening client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(tags1, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(tags1 != null) + { + _requestContent = SafeJsonConvert.SerializeObject(tags1, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ExplicitModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ExplicitModel.cs index 6d1908994fb20..f0e42c1bf7fc9 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ExplicitModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ExplicitModel.cs @@ -99,9 +99,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -220,9 +223,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -331,9 +337,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -456,9 +465,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -805,9 +817,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -926,9 +941,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1044,9 +1062,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1172,9 +1193,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1532,9 +1556,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1657,9 +1684,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1779,9 +1809,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1911,9 +1944,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2023,9 +2059,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2144,9 +2183,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2262,9 +2304,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2390,9 +2435,12 @@ public ExplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ImplicitModel.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ImplicitModel.cs index e07c894c0febb..52a2bd5e9c8a0 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ImplicitModel.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/RequiredOptional/ImplicitModel.cs @@ -446,9 +446,12 @@ public ImplicitModel(AutoRestRequiredOptionalTestService client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(bodyParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(bodyParameter, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs index 518a34aeade57..d8f9e2c761579 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/IPaths.cs @@ -277,5 +277,46 @@ public partial interface IPaths /// The cancellation token. /// Task DateTimeNullWithHttpMessagesAsync(DateTime dateTimePath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get 'lorem' encoded value as 'bG9yZW0' (base64url) + /// + /// + /// base64url encoded value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task Base64UrlWithHttpMessagesAsync(byte[] base64UrlPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get an array of string ['ArrayPath1', 'begin!*'();:@ + /// &=+$,/?#[]end' , null, ''] using the csv-array format + /// + /// + /// an array of string ['ArrayPath1', 'begin!*'();:@ + /// &=+$,/?#[]end' , null, ''] using the csv-array format + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task ArrayCsvInPathWithHttpMessagesAsync(IList arrayPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); + /// + /// Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + /// + /// + /// Unix time encoded value + /// + /// + /// The headers that will be added to request. + /// + /// + /// The cancellation token. + /// + Task UnixTimeUrlWithHttpMessagesAsync(DateTime unixTimeUrlPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs index b68b6a5103255..3892f728ba11b 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/Paths.cs @@ -2470,5 +2470,333 @@ public Paths(AutoRestUrlTestService client) return _result; } + /// + /// Get 'lorem' encoded value as 'bG9yZW0' (base64url) + /// + /// + /// base64url encoded value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task Base64UrlWithHttpMessagesAsync(byte[] base64UrlPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (base64UrlPath == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "base64UrlPath"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("base64UrlPath", base64UrlPath); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "Base64Url", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "paths/string/bG9yZW0/{base64UrlPath}").ToString(); + _url = _url.Replace("{base64UrlPath}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(base64UrlPath, new Base64UrlJsonConverter()).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task ArrayCsvInPathWithHttpMessagesAsync(IList arrayPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + if (arrayPath == null) + { + throw new ValidationException(ValidationRules.CannotBeNull, "arrayPath"); + } + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("arrayPath", arrayPath); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "ArrayCsvInPath", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath:commaSeparated}").ToString(); + _url = _url.Replace("{arrayPath:commaSeparated}", Uri.EscapeDataString(string.Join(",", arrayPath))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + + /// + /// Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + /// + /// + /// Unix time encoded value + /// + /// + /// Headers that will be added to request. + /// + /// + /// The cancellation token. + /// + /// + /// A response object containing the response body and response headers. + /// + public async Task UnixTimeUrlWithHttpMessagesAsync(DateTime unixTimeUrlPath, Dictionary> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) + { + // Tracing + bool _shouldTrace = ServiceClientTracing.IsEnabled; + string _invocationId = null; + if (_shouldTrace) + { + _invocationId = ServiceClientTracing.NextInvocationId.ToString(); + Dictionary tracingParameters = new Dictionary(); + tracingParameters.Add("unixTimeUrlPath", unixTimeUrlPath); + tracingParameters.Add("cancellationToken", cancellationToken); + ServiceClientTracing.Enter(_invocationId, this, "UnixTimeUrl", tracingParameters); + } + // Construct URL + var _baseUrl = this.Client.BaseUri.AbsoluteUri; + var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "paths/int/1460505600/{unixTimeUrlPath}").ToString(); + _url = _url.Replace("{unixTimeUrlPath}", Uri.EscapeDataString(SafeJsonConvert.SerializeObject(unixTimeUrlPath, new UnixTimeJsonConverter()).Trim('"'))); + // Create HTTP transport objects + HttpRequestMessage _httpRequest = new HttpRequestMessage(); + HttpResponseMessage _httpResponse = null; + _httpRequest.Method = new HttpMethod("GET"); + _httpRequest.RequestUri = new Uri(_url); + // Set Headers + if (customHeaders != null) + { + foreach(var _header in customHeaders) + { + if (_httpRequest.Headers.Contains(_header.Key)) + { + _httpRequest.Headers.Remove(_header.Key); + } + _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); + } + } + + // Serialize Request + string _requestContent = null; + // Send Request + if (_shouldTrace) + { + ServiceClientTracing.SendRequest(_invocationId, _httpRequest); + } + cancellationToken.ThrowIfCancellationRequested(); + _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); + if (_shouldTrace) + { + ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); + } + HttpStatusCode _statusCode = _httpResponse.StatusCode; + cancellationToken.ThrowIfCancellationRequested(); + string _responseContent = null; + if ((int)_statusCode != 200) + { + var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); + try + { + _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); + Error _errorBody = SafeJsonConvert.DeserializeObject(_responseContent, this.Client.DeserializationSettings); + if (_errorBody != null) + { + ex.Body = _errorBody; + } + } + catch (JsonException) + { + // Ignore the exception + } + ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); + ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); + if (_shouldTrace) + { + ServiceClientTracing.Error(_invocationId, ex); + } + _httpRequest.Dispose(); + if (_httpResponse != null) + { + _httpResponse.Dispose(); + } + throw ex; + } + // Create Result + var _result = new HttpOperationResponse(); + _result.Request = _httpRequest; + _result.Response = _httpResponse; + if (_shouldTrace) + { + ServiceClientTracing.Exit(_invocationId, _result); + } + return _result; + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs index 253b845261892..b4e8d2ce268e6 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Url/PathsExtensions.cs @@ -646,5 +646,102 @@ public static void DateTimeNull(this IPaths operations, DateTime dateTimePath) await operations.DateTimeNullWithHttpMessagesAsync(dateTimePath, null, cancellationToken).ConfigureAwait(false); } + /// + /// Get 'lorem' encoded value as 'bG9yZW0' (base64url) + /// + /// + /// The operations group for this extension method. + /// + /// + /// base64url encoded value + /// + public static void Base64Url(this IPaths operations, byte[] base64UrlPath) + { + Task.Factory.StartNew(s => ((IPaths)s).Base64UrlAsync(base64UrlPath), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get 'lorem' encoded value as 'bG9yZW0' (base64url) + /// + /// + /// The operations group for this extension method. + /// + /// + /// base64url encoded value + /// + /// + /// The cancellation token. + /// + public static async Task Base64UrlAsync(this IPaths operations, byte[] base64UrlPath, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.Base64UrlWithHttpMessagesAsync(base64UrlPath, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// The operations group for this extension method. + /// + /// + /// an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + public static void ArrayCsvInPath(this IPaths operations, IList arrayPath) + { + Task.Factory.StartNew(s => ((IPaths)s).ArrayCsvInPathAsync(arrayPath), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// The operations group for this extension method. + /// + /// + /// an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + /// null, ''] using the csv-array format + /// + /// + /// The cancellation token. + /// + public static async Task ArrayCsvInPathAsync(this IPaths operations, IList arrayPath, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.ArrayCsvInPathWithHttpMessagesAsync(arrayPath, null, cancellationToken).ConfigureAwait(false); + } + + /// + /// Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + /// + /// + /// The operations group for this extension method. + /// + /// + /// Unix time encoded value + /// + public static void UnixTimeUrl(this IPaths operations, DateTime unixTimeUrlPath) + { + Task.Factory.StartNew(s => ((IPaths)s).UnixTimeUrlAsync(unixTimeUrlPath), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); + } + + /// + /// Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + /// + /// + /// The operations group for this extension method. + /// + /// + /// Unix time encoded value + /// + /// + /// The cancellation token. + /// + public static async Task UnixTimeUrlAsync(this IPaths operations, DateTime unixTimeUrlPath, CancellationToken cancellationToken = default(CancellationToken)) + { + await operations.UnixTimeUrlWithHttpMessagesAsync(unixTimeUrlPath, null, cancellationToken).ConfigureAwait(false); + } + } } diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Validation/AutoRestValidationTest.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Validation/AutoRestValidationTest.cs index dd33131940bbd..73459ebb73386 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Validation/AutoRestValidationTest.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/Validation/AutoRestValidationTest.cs @@ -461,9 +461,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -679,9 +682,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/DateTimeOffset/SwaggerDateTimeOffsetClient.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/DateTimeOffset/SwaggerDateTimeOffsetClient.cs index b59cf0b0fe805..3bd502e2cd4ac 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/DateTimeOffset/SwaggerDateTimeOffsetClient.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/DateTimeOffset/SwaggerDateTimeOffsetClient.cs @@ -208,9 +208,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -346,9 +349,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -484,9 +490,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -622,9 +631,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Polymorphic/PolymorphicAnimalStore.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Polymorphic/PolymorphicAnimalStore.cs index 9dbebd699667a..86bf0ccd5653a 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Polymorphic/PolymorphicAnimalStore.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Polymorphic/PolymorphicAnimalStore.cs @@ -202,9 +202,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(animalCreateOrUpdateParameter, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(animalCreateOrUpdateParameter != null) + { + _requestContent = SafeJsonConvert.SerializeObject(animalCreateOrUpdateParameter, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/Models/Product.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/Models/Product.cs index 2c3e2bafc98f6..d2ea149e267a9 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/Models/Product.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/Models/Product.cs @@ -25,7 +25,7 @@ public Product() { } /// /// Initializes a new instance of the Product class. /// - public Product(int? integer = default(int?), int? intProperty = default(int?), long? longProperty = default(long?), double? number = default(double?), double? floatProperty = default(double?), double? doubleProperty = default(double?), byte[] byteProperty = default(byte[]), string stringProperty = default(string), Guid? uuid = default(Guid?), string enumProperty = default(string), bool? boolean = default(bool?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), IList integerArray = default(IList), IList intArray = default(IList), IList longArray = default(IList), IList numberArray = default(IList), IList floatArray = default(IList), IList doubleArray = default(IList), IList byteArray = default(IList), IList booleanArray = default(IList), IList stringArray = default(IList), IList dateArray = default(IList), IList dateTimeArray = default(IList), IList uuidArray = default(IList)) + public Product(int? integer = default(int?), int? intProperty = default(int?), long? longProperty = default(long?), double? number = default(double?), double? floatProperty = default(double?), double? doubleProperty = default(double?), byte[] byteProperty = default(byte[]), string stringProperty = default(string), byte[] base64url = default(byte[]), Guid? uuid = default(Guid?), string enumProperty = default(string), bool? boolean = default(bool?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), IList integerArray = default(IList), IList intArray = default(IList), IList longArray = default(IList), IList numberArray = default(IList), IList floatArray = default(IList), IList doubleArray = default(IList), IList byteArray = default(IList), IList booleanArray = default(IList), IList stringArray = default(IList), IList base64urlArray = default(IList), IList dateArray = default(IList), IList dateTimeArray = default(IList), IList uuidArray = default(IList)) { Integer = integer; IntProperty = intProperty; @@ -35,6 +35,7 @@ public Product() { } DoubleProperty = doubleProperty; ByteProperty = byteProperty; StringProperty = stringProperty; + Base64url = base64url; Uuid = uuid; EnumProperty = enumProperty; Boolean = boolean; @@ -49,6 +50,7 @@ public Product() { } ByteArray = byteArray; BooleanArray = booleanArray; StringArray = stringArray; + Base64urlArray = base64urlArray; DateArray = dateArray; DateTimeArray = dateTimeArray; UuidArray = uuidArray; @@ -94,6 +96,12 @@ public Product() { } [JsonProperty(PropertyName = "string")] public string StringProperty { get; set; } + /// + /// + [JsonConverter(typeof(Base64UrlJsonConverter))] + [JsonProperty(PropertyName = "base64url")] + public byte[] Base64url { get; set; } + /// /// [JsonProperty(PropertyName = "uuid")] @@ -166,6 +174,11 @@ public Product() { } [JsonProperty(PropertyName = "stringArray")] public IList StringArray { get; set; } + /// + /// + [JsonProperty(PropertyName = "base64urlArray")] + public IList Base64urlArray { get; set; } + /// /// [JsonProperty(PropertyName = "dateArray")] diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/SwaggerDataTypesClient.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/SwaggerDataTypesClient.cs index 30a57dd8f7f38..bc41c9c9bd812 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/SwaggerDataTypesClient.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Primitives/SwaggerDataTypesClient.cs @@ -208,9 +208,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -346,9 +349,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -484,9 +490,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -622,9 +631,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(product != null) + { + _requestContent = SafeJsonConvert.SerializeObject(product, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.RecursiveTypes/RecursiveTypesAPI.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.RecursiveTypes/RecursiveTypesAPI.cs index 68210edc4dab2..ae58814c3bdb7 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.RecursiveTypes/RecursiveTypesAPI.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.RecursiveTypes/RecursiveTypesAPI.cs @@ -227,9 +227,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Sequences/SequenceRequestResponseTest.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Sequences/SequenceRequestResponseTest.cs index e3e054da32ea1..8548cb8d729d7 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Sequences/SequenceRequestResponseTest.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/Mirror.Sequences/SequenceRequestResponseTest.cs @@ -211,9 +211,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(pets, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(pets != null) + { + _requestContent = SafeJsonConvert.SerializeObject(pets, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -341,9 +344,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(petStyle != null) + { + _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -471,9 +477,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(petStyle != null) + { + _requestContent = SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2/SwaggerPetstoreV2.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2/SwaggerPetstoreV2.cs index 9839ee82c0df4..9245c2c40a070 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2/SwaggerPetstoreV2.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Expected/PetstoreV2/SwaggerPetstoreV2.cs @@ -323,9 +323,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -451,9 +454,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -1306,9 +1312,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -1679,9 +1688,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -1785,9 +1797,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -1891,9 +1906,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { @@ -2379,9 +2397,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Credentials != null) { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Swagger/swagger-mirror-primitives.json b/AutoRest/Generators/CSharp/CSharp.Tests/Swagger/swagger-mirror-primitives.json index 3fa190be4cf05..91fa027d2107c 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Swagger/swagger-mirror-primitives.json +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Swagger/swagger-mirror-primitives.json @@ -185,6 +185,10 @@ "string": { "type": "string" }, + "base64url": { + "type": "string", + "format": "base64url" + }, "uuid": { "type": "string", "format": "uuid" @@ -244,7 +248,7 @@ "format": "double" } }, - "byteArray": { + "byteArray": { "type": "array", "items": { "type": "string", @@ -263,6 +267,13 @@ "type": "string" } }, + "base64urlArray": { + "type": "array", + "items": { + "type": "string", + "format": "base64url" + } + }, "dateArray": { "type": "array", "items": { diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/Utilities/MirrorTestHelpers.cs b/AutoRest/Generators/CSharp/CSharp.Tests/Utilities/MirrorTestHelpers.cs index 0710d373ee783..513368cb1f4cf 100644 --- a/AutoRest/Generators/CSharp/CSharp.Tests/Utilities/MirrorTestHelpers.cs +++ b/AutoRest/Generators/CSharp/CSharp.Tests/Utilities/MirrorTestHelpers.cs @@ -34,7 +34,8 @@ public static Product GenerateProduct() DateTime = DateTime.UtcNow, Uuid = new Guid("122F1443-D736-4C16-8207-06B978AA4FF9"), ByteArray = - new List {GenerateBytes(100), GenerateBytes(200), GenerateBytes(300), GenerateBytes(100)} + new List { GenerateBytes(100), GenerateBytes(200), GenerateBytes(300), GenerateBytes(100) }, + Base64url = System.Text.Encoding.UTF8.GetBytes("Now is the time for all good men to come to the aid of their country") }; } @@ -72,6 +73,7 @@ public static void ValidateProduct(Product expected, Product actual) Assert.Equal(expected.StringProperty, actual.StringProperty); Assert.Equal(expected.DateTime, actual.DateTime); Assert.Equal(expected.Uuid, actual.Uuid); + Assert.Equal(expected.Base64url, actual.Base64url); ValidateList(expected.ByteArray, actual.ByteArray, (s, t) => Assert.Equal(s, t)); } diff --git a/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs b/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs index b0a43b1bc5431..b43de08e365b0 100644 --- a/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs +++ b/AutoRest/Generators/CSharp/CSharp/CSharpCodeGenerator.cs @@ -14,7 +14,7 @@ namespace Microsoft.Rest.Generator.CSharp public class CSharpCodeGenerator : CodeGenerator { private readonly CSharpCodeNamer _namer; - private const string ClientRuntimePackage = "Microsoft.Rest.ClientRuntime.2.1.0"; + private const string ClientRuntimePackage = "Microsoft.Rest.ClientRuntime.2.2.0"; public CSharpCodeGenerator(Settings settings) : base(settings) { diff --git a/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs b/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs index bd368f3f4262e..3504b01cb57d2 100644 --- a/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs +++ b/AutoRest/Generators/CSharp/CSharp/CSharpCodeNamer.cs @@ -237,7 +237,11 @@ protected virtual IType NormalizePrimaryType(PrimaryType primaryType) return null; } - if (primaryType.Type == KnownPrimaryType.Boolean) + if (primaryType.Type == KnownPrimaryType.Base64Url) + { + primaryType.Name = "byte[]"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) { primaryType.Name = "bool"; } @@ -293,6 +297,10 @@ protected virtual IType NormalizePrimaryType(PrimaryType primaryType) { primaryType.Name = "ServiceClientCredentials"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + primaryType.Name = "DateTime"; + } else if (primaryType.Type == KnownPrimaryType.Uuid) { primaryType.Name = "Guid"; @@ -396,7 +404,9 @@ public override string EscapeDefaultValue(string defaultValue, IType type) primaryType.Type == KnownPrimaryType.DateTime || primaryType.Type == KnownPrimaryType.DateTimeRfc1123 || primaryType.Type == KnownPrimaryType.TimeSpan || - primaryType.Type == KnownPrimaryType.ByteArray) + primaryType.Type == KnownPrimaryType.ByteArray || + primaryType.Type == KnownPrimaryType.Base64Url || + primaryType.Type == KnownPrimaryType.UnixTime) { return "SafeJsonConvert.DeserializeObject<" + primaryType.Name.TrimEnd('?') + diff --git a/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs b/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs index 6e98dcce5997e..ae4d9f11159de 100644 --- a/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs +++ b/AutoRest/Generators/CSharp/CSharp/ClientModelExtensions.cs @@ -221,6 +221,14 @@ public static string ToString(this IType type, string clientReference, string re { serializationSettings = "new DateTimeRfc1123JsonConverter()"; } + else if (primaryType.Type == KnownPrimaryType.Base64Url) + { + serializationSettings = "new Base64UrlJsonConverter()"; + } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + serializationSettings = "new UnixTimeJsonConverter()"; + } } return string.Format(CultureInfo.InvariantCulture, @@ -264,6 +272,7 @@ public static bool IsValueType(this IType type) || primaryType.Type == KnownPrimaryType.Long || primaryType.Type == KnownPrimaryType.TimeSpan || primaryType.Type == KnownPrimaryType.DateTimeRfc1123 + || primaryType.Type == KnownPrimaryType.UnixTime || primaryType.Type == KnownPrimaryType.Uuid)); } diff --git a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs index f286b20fd7b84..22d1ca54614d0 100644 --- a/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/CSharp/CSharp/TemplateModels/MethodTemplateModel.cs @@ -8,6 +8,7 @@ using System.Net; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Utilities; +using System.Text.RegularExpressions; namespace Microsoft.Rest.Generator.CSharp { @@ -324,24 +325,22 @@ public string ClientReference /// public string GetSerializationSettingsReference(IType serializationType) { - SequenceType sequenceType = serializationType as SequenceType; - DictionaryType dictionaryType = serializationType as DictionaryType; - if (serializationType.IsPrimaryType(KnownPrimaryType.Date) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.Date) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.Date)) + if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date)) { return "new DateJsonConverter()"; } - else if (serializationType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.DateTimeRfc1123) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.DateTimeRfc1123)) + else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) { return "new DateTimeRfc1123JsonConverter()"; } + else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url)) + { + return "new Base64UrlJsonConverter()"; + } + else if (serializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime)) + { + return "new UnixTimeJsonConverter()"; + } return ClientReference + ".SerializationSettings"; } @@ -352,17 +351,18 @@ public string GetSerializationSettingsReference(IType serializationType) /// public string GetDeserializationSettingsReference(IType deserializationType) { - SequenceType sequenceType = deserializationType as SequenceType; - DictionaryType dictionaryType = deserializationType as DictionaryType; - if (deserializationType.IsPrimaryType(KnownPrimaryType.Date) || - (sequenceType != null && sequenceType.ElementType is PrimaryType - && ((PrimaryType)sequenceType.ElementType).Type == KnownPrimaryType.Date) || - (dictionaryType != null && dictionaryType.ValueType is PrimaryType - && ((PrimaryType)dictionaryType.ValueType).Type == KnownPrimaryType.Date)) + if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Date)) { return "new DateJsonConverter()"; } - + else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.Base64Url)) + { + return "new Base64UrlJsonConverter()"; + } + else if (deserializationType.IsOrContainsPrimaryType(KnownPrimaryType.UnixTime)) + { + return "new UnixTimeJsonConverter()"; + } return ClientReference + ".DeserializationSettings"; } @@ -396,10 +396,28 @@ public virtual string BuildUrl(string variableName) replaceString = "{0} = {0}.Replace(\"{{{1}}}\", {2});"; } - builder.AppendLine(replaceString, + var urlPathName = pathParameter.SerializedName; + string pat = @".*\{" + urlPathName + @"(\:\w+)\}"; + Regex r = new Regex(pat); + Match m = r.Match(Url); + if (m.Success) + { + urlPathName += m.Groups[1].Value; + } + if (pathParameter.Type is SequenceType) + { + builder.AppendLine(replaceString, + variableName, + urlPathName, + pathParameter.GetFormattedReferenceValue(ClientReference)); + } + else + { + builder.AppendLine(replaceString, variableName, - pathParameter.SerializedName, + urlPathName, pathParameter.Type.ToString(ClientReference, pathParameter.Name)); + } } if (this.LogicalParameterTemplateModels.Any(p => p.Location == ParameterLocation.Query)) { diff --git a/AutoRest/Generators/CSharp/CSharp/Templates/MethodTemplate.cshtml b/AutoRest/Generators/CSharp/CSharp/Templates/MethodTemplate.cshtml index b81e369d21565..df038116b29cb 100644 --- a/AutoRest/Generators/CSharp/CSharp/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/CSharp/CSharp/Templates/MethodTemplate.cshtml @@ -161,11 +161,12 @@ else } else { - - _requestContent = SafeJsonConvert.SerializeObject(@(Model.RequestBody.Name), @(Model.GetSerializationSettingsReference(Model.RequestBody.Type))); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("@(Model.RequestContentType)"); - + @:if(@(Model.RequestBody.Name) != null) + @:{ + @:_requestContent = SafeJsonConvert.SerializeObject(@(Model.RequestBody.Name), @(Model.GetSerializationSettingsReference(Model.RequestBody.Type))); + @:_httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + @:_httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("@(Model.RequestContentType)"); + @:} } } else if (Model.LogicalParameters.Where(p => p.Location == ParameterLocation.FormData).Any()) diff --git a/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml b/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml index 7807c491ce63e..942e67ef809e3 100644 --- a/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/CSharp/CSharp/Templates/ModelTemplate.cshtml @@ -119,6 +119,14 @@ namespace @(Settings.Namespace).Models { @:[JsonConverter(typeof(DateTimeRfc1123JsonConverter))] } + if (property.Type.IsPrimaryType(KnownPrimaryType.Base64Url)) + { + @:[JsonConverter(typeof(Base64UrlJsonConverter))] + } + if (property.Type.IsPrimaryType(KnownPrimaryType.UnixTime)) + { + @:[JsonConverter(typeof(UnixTimeJsonConverter))] + } @:[JsonProperty(PropertyName = "@property.SerializedName")] @:public @property.Type.Name @property.Name { get; @(property.IsReadOnly ? "private " : "")set; } @EmptyLine @@ -137,6 +145,14 @@ namespace @(Settings.Namespace).Models { @:[JsonConverter(typeof(DateTimeRfc1123JsonConverter))] } + if (property.Type.IsPrimaryType(KnownPrimaryType.Base64Url)) + { + @:[JsonConverter(typeof(Base64UrlJsonConverter))] + } + if (property.Type.IsPrimaryType(KnownPrimaryType.UnixTime)) + { + @:[JsonConverter(typeof(UnixTimeJsonConverter))] + } @:[JsonProperty(PropertyName = "@property.SerializedName")] @:public static @property.Type.Name @property.Name { get; private set; } @EmptyLine diff --git a/AutoRest/Generators/Extensions/Extensions.Tests/ExtensionsTests.cs b/AutoRest/Generators/Extensions/Extensions.Tests/ExtensionsTests.cs index dc5dc9154620d..7c11fadab6eae 100644 --- a/AutoRest/Generators/Extensions/Extensions.Tests/ExtensionsTests.cs +++ b/AutoRest/Generators/Extensions/Extensions.Tests/ExtensionsTests.cs @@ -193,7 +193,7 @@ public void TestClientNameJavaNormalization() var modeler = new SwaggerModeler(setting); var clientModel = modeler.Build(); Extensions.NormalizeClientModel(clientModel, setting); - var namer = new Microsoft.Rest.Generator.Java.JavaCodeNamer(); + var namer = new Microsoft.Rest.Generator.Java.JavaCodeNamer(setting.Namespace); namer.NormalizeClientModel(clientModel); Assert.NotNull(clientModel); diff --git a/AutoRest/Generators/Extensions/Extensions/Extensions.cs b/AutoRest/Generators/Extensions/Extensions/Extensions.cs index e3e07511f3168..620a2d594c83e 100644 --- a/AutoRest/Generators/Extensions/Extensions/Extensions.cs +++ b/AutoRest/Generators/Extensions/Extensions/Extensions.cs @@ -12,6 +12,8 @@ using Microsoft.Rest.Modeler.Swagger.Model; using Newtonsoft.Json.Linq; using Newtonsoft.Json; +using System.Text.RegularExpressions; +using Microsoft.Rest.Generator.Properties; namespace Microsoft.Rest.Generator { @@ -27,6 +29,8 @@ public abstract class Extensions public const string FlattenOriginalTypeName = "x-ms-client-flatten-original-type-name"; public const string ParameterGroupExtension = "x-ms-parameter-grouping"; public const string ParameterizedHostExtension = "x-ms-parameterized-host"; + public const string UseSchemePrefix = "useSchemePrefix"; + public const string PositionInOperation = "positionInOperation"; private static bool hostChecked = false; @@ -67,6 +71,28 @@ public static void ProcessParameterizedHost(ServiceClient serviceClient, Setting { var hostTemplate = (string)hostExtension["hostTemplate"]; var parametersJson = hostExtension["parameters"].ToString(); + var useSchemePrefix = true; + if (hostExtension[UseSchemePrefix] != null) + { + useSchemePrefix = bool.Parse(hostExtension[UseSchemePrefix].ToString()); + } + + var position = "first"; + + if (hostExtension[PositionInOperation] != null) + { + var pat = "^(fir|la)st$"; + Regex r = new Regex(pat, RegexOptions.IgnoreCase); + var text = hostExtension[PositionInOperation].ToString(); + Match m = r.Match(text); + if (!m.Success) + { + throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, + Resources.InvalidExtensionProperty, text, PositionInOperation, ParameterizedHostExtension, "first, last")); + } + position = text; + } + if (!string.IsNullOrEmpty(parametersJson)) { var jsonSettings = new JsonSerializerSettings @@ -76,7 +102,7 @@ public static void ProcessParameterizedHost(ServiceClient serviceClient, Setting }; var swaggerParams = JsonConvert.DeserializeObject>(parametersJson, jsonSettings); - + List hostParamList = new List(); foreach (var swaggerParameter in swaggerParams) { // Build parameter @@ -89,16 +115,33 @@ public static void ProcessParameterizedHost(ServiceClient serviceClient, Setting parameter.ClientProperty = serviceClient.Properties.Single(p => p.SerializedName.Equals(parameter.SerializedName)); } parameter.Extensions["hostParameter"] = true; + hostParamList.Add(parameter); + } - foreach (var method in serviceClient.Methods) + foreach (var method in serviceClient.Methods) + { + if (position.Equals("first", StringComparison.OrdinalIgnoreCase)) { - method.Parameters.Add(parameter); + method.Parameters.InsertRange(0, hostParamList); } + else + { + method.Parameters.AddRange(hostParamList); + } + } - - serviceClient.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}", - modeler.ServiceDefinition.Schemes[0].ToString().ToLowerInvariant(), - hostTemplate, modeler.ServiceDefinition.BasePath); + if (useSchemePrefix) + { + serviceClient.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}", + modeler.ServiceDefinition.Schemes[0].ToString().ToLowerInvariant(), + hostTemplate, modeler.ServiceDefinition.BasePath); + } + else + { + serviceClient.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}{1}", + hostTemplate, modeler.ServiceDefinition.BasePath); + } + } } } @@ -201,7 +244,7 @@ private static IEnumerable FlattenProperty(Property propertyToFlatten, } List extractedProperties = new List(); - foreach (Property innerProperty in typeToFlatten.Properties) + foreach (Property innerProperty in typeToFlatten.ComposedProperties) { Debug.Assert(typeToFlatten.SerializedName != null); Debug.Assert(innerProperty.SerializedName != null); diff --git a/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs b/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs index 689a601b826f3..f98e2ea0b022c 100644 --- a/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs +++ b/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs @@ -69,6 +69,15 @@ internal static string HeadMethodInvalidResponses { } } + /// + /// Looks up a localized string similar to The value '{0}' provided for property '{1}' of extension '{2} is invalid. Valid values are: '{3}'.. + /// + internal static string InvalidExtensionProperty { + get { + return ResourceManager.GetString("InvalidExtensionProperty", resourceCulture); + } + } + /// /// Looks up a localized string similar to Azure resource {0} is missing required 'properties' property.. /// diff --git a/AutoRest/Generators/Extensions/Extensions/Properties/Resources.resx b/AutoRest/Generators/Extensions/Extensions/Properties/Resources.resx index d06a580a716fe..7df584f0a47aa 100644 --- a/AutoRest/Generators/Extensions/Extensions/Properties/Resources.resx +++ b/AutoRest/Generators/Extensions/Extensions/Properties/Resources.resx @@ -120,6 +120,9 @@ Head method '{0}' should contain only 200 level responses, or 404. + + The value '{0}' provided for property '{1}' of extension '{2} is invalid. Valid values are: '{3}'. + Azure resource {0} is missing required 'properties' property. diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java index c9daca73b5a07..26385d6c09481 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azureparametergrouping/ParameterGroupingOperationsImpl.java @@ -153,13 +153,7 @@ private ServiceResponse postRequiredDelegate(Response respon public ServiceResponse postOptional() throws ErrorException, IOException { final ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = null; String customHeader = null; - if (parameterGroupingPostOptionalParameters != null) { - customHeader = parameterGroupingPostOptionalParameters.getCustomHeader(); - } Integer query = null; - if (parameterGroupingPostOptionalParameters != null) { - query = parameterGroupingPostOptionalParameters.getQuery(); - } Call call = service.postOptional(this.client.getAcceptLanguage(), customHeader, query); return postOptionalDelegate(call.execute()); } @@ -177,13 +171,7 @@ public ServiceCall postOptionalAsync(final ServiceCallback serviceCallback } final ParameterGroupingPostOptionalParameters parameterGroupingPostOptionalParameters = null; String customHeader = null; - if (parameterGroupingPostOptionalParameters != null) { - customHeader = parameterGroupingPostOptionalParameters.getCustomHeader(); - } Integer query = null; - if (parameterGroupingPostOptionalParameters != null) { - query = parameterGroupingPostOptionalParameters.getQuery(); - } Call call = service.postOptional(this.client.getAcceptLanguage(), customHeader, query); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @@ -275,21 +263,9 @@ public ServiceResponse postMultiParamGroups() throws ErrorException, IOExc final FirstParameterGroup firstParameterGroup = null; final ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = null; String headerOne = null; - if (firstParameterGroup != null) { - headerOne = firstParameterGroup.getHeaderOne(); - } Integer queryOne = null; - if (firstParameterGroup != null) { - queryOne = firstParameterGroup.getQueryOne(); - } String headerTwo = null; - if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { - headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.getHeaderTwo(); - } Integer queryTwo = null; - if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { - queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.getQueryTwo(); - } Call call = service.postMultiParamGroups(this.client.getAcceptLanguage(), headerOne, queryOne, headerTwo, queryTwo); return postMultiParamGroupsDelegate(call.execute()); } @@ -308,21 +284,9 @@ public ServiceCall postMultiParamGroupsAsync(final ServiceCallback service final FirstParameterGroup firstParameterGroup = null; final ParameterGroupingPostMultiParamGroupsSecondParamGroup parameterGroupingPostMultiParamGroupsSecondParamGroup = null; String headerOne = null; - if (firstParameterGroup != null) { - headerOne = firstParameterGroup.getHeaderOne(); - } Integer queryOne = null; - if (firstParameterGroup != null) { - queryOne = firstParameterGroup.getQueryOne(); - } String headerTwo = null; - if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { - headerTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.getHeaderTwo(); - } Integer queryTwo = null; - if (parameterGroupingPostMultiParamGroupsSecondParamGroup != null) { - queryTwo = parameterGroupingPostMultiParamGroupsSecondParamGroup.getQueryTwo(); - } Call call = service.postMultiParamGroups(this.client.getAcceptLanguage(), headerOne, queryOne, headerTwo, queryTwo); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @@ -433,13 +397,7 @@ private ServiceResponse postMultiParamGroupsDelegate(Response postSharedParameterGroupObject() throws ErrorException, IOException { final FirstParameterGroup firstParameterGroup = null; String headerOne = null; - if (firstParameterGroup != null) { - headerOne = firstParameterGroup.getHeaderOne(); - } Integer queryOne = null; - if (firstParameterGroup != null) { - queryOne = firstParameterGroup.getQueryOne(); - } Call call = service.postSharedParameterGroupObject(this.client.getAcceptLanguage(), headerOne, queryOne); return postSharedParameterGroupObjectDelegate(call.execute()); } @@ -457,13 +415,7 @@ public ServiceCall postSharedParameterGroupObjectAsync(final ServiceCallback call = service.postSharedParameterGroupObject(this.client.getAcceptLanguage(), headerOne, queryOne); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java index d8ff6ea5bd65b..75777653172cf 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/azurespecials/OdataOperationsImpl.java @@ -57,7 +57,7 @@ public OdataOperationsImpl(Retrofit retrofit, AutoRestAzureSpecialParametersTest interface OdataService { @Headers("Content-Type: application/json; charset=utf-8") @GET("azurespecials/odata/filter") - Call getWithFilter(@Query("$filter") String filter, @Query("$top") Integer top, @Query("$orderby") String orderby, @Header("accept-language") String acceptLanguage); + Call getWithFilter(@Query("$filter") OdataFilter filter, @Query("$top") Integer top, @Query("$orderby") String orderby, @Header("accept-language") String acceptLanguage); } @@ -72,7 +72,7 @@ public ServiceResponse getWithFilter() throws ErrorException, IOException final OdataFilter filter = null; final Integer top = null; final String orderby = null; - Call call = service.getWithFilter(this.client.getMapperAdapter().serializeRaw(filter), top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); return getWithFilterDelegate(call.execute()); } @@ -90,7 +90,7 @@ public ServiceCall getWithFilterAsync(final ServiceCallback serviceCallbac final OdataFilter filter = null; final Integer top = null; final String orderby = null; - Call call = service.getWithFilter(this.client.getMapperAdapter().serializeRaw(filter), top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -117,7 +117,7 @@ public void onResponse(Call call, Response response) */ public ServiceResponse getWithFilter(OdataFilter filter, Integer top, String orderby) throws ErrorException, IOException { Validator.validate(filter); - Call call = service.getWithFilter(this.client.getMapperAdapter().serializeRaw(filter), top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); return getWithFilterDelegate(call.execute()); } @@ -136,7 +136,7 @@ public ServiceCall getWithFilterAsync(OdataFilter filter, Integer top, String or throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(filter, serviceCallback); - Call call = service.getWithFilter(this.client.getMapperAdapter().serializeRaw(filter), top, orderby, this.client.getAcceptLanguage()); + Call call = service.getWithFilter(filter, top, orderby, this.client.getAcceptLanguage()); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperations.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperations.java index a7faf0d1d9b85..7ca9a529752e3 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperations.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperations.java @@ -26,7 +26,7 @@ public interface HttpSuccessOperations { * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse head200() throws CloudException, IOException; @@ -44,7 +44,7 @@ public interface HttpSuccessOperations { * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse head204() throws CloudException, IOException; @@ -62,7 +62,7 @@ public interface HttpSuccessOperations { * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse head404() throws CloudException, IOException; diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperationsImpl.java index 7848477599c2a..b3f31dbd8a2c2 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/head/HttpSuccessOperationsImpl.java @@ -70,7 +70,7 @@ interface HttpSuccessService { * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse head200() throws CloudException, IOException { Call call = service.head200(this.client.getAcceptLanguage()); @@ -116,7 +116,7 @@ private ServiceResponse head200Delegate(Response response) throws * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse head204() throws CloudException, IOException { Call call = service.head204(this.client.getAcceptLanguage()); @@ -162,7 +162,7 @@ private ServiceResponse head204Delegate(Response response) throws * * @throws CloudException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse head404() throws CloudException, IOException { Call call = service.head404(this.client.getAcceptLanguage()); diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java index 04e7b511039b5..cf41764797840 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/paging/PagingOperationsImpl.java @@ -199,19 +199,13 @@ public ServiceResponse> getMultiplePages() throws CloudExcept final String clientRequestId = null; final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; Integer maxresults = null; - if (pagingGetMultiplePagesOptions != null) { - maxresults = pagingGetMultiplePagesOptions.getMaxresults(); - } Integer timeout = null; - if (pagingGetMultiplePagesOptions != null) { - timeout = pagingGetMultiplePagesOptions.getTimeout(); - } Call call = service.getMultiplePages(clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); ServiceResponse> response = getMultiplePagesDelegate(call.execute()); PagedList result = new PagedList(response.getBody()) { @Override public Page nextPage(String nextPageLink) throws CloudException, IOException { - return getMultiplePagesNext(nextPageLink, clientRequestId, pagingGetMultiplePagesOptions).getBody(); + return getMultiplePagesNext(nextPageLink, null, null).getBody(); } }; return new ServiceResponse<>(result, response.getResponse()); @@ -231,13 +225,7 @@ public ServiceCall getMultiplePagesAsync(final ListOperationCallback se final String clientRequestId = null; final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; Integer maxresults = null; - if (pagingGetMultiplePagesOptions != null) { - maxresults = pagingGetMultiplePagesOptions.getMaxresults(); - } Integer timeout = null; - if (pagingGetMultiplePagesOptions != null) { - timeout = pagingGetMultiplePagesOptions.getTimeout(); - } Call call = service.getMultiplePages(clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @@ -248,7 +236,7 @@ public void onResponse(Call call, Response response) serviceCallback.load(result.getBody().getItems()); if (result.getBody().getNextPageLink() != null && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getMultiplePagesNextAsync(result.getBody().getNextPageLink(), clientRequestId, pagingGetMultiplePagesOptions, serviceCall, serviceCallback); + getMultiplePagesNextAsync(result.getBody().getNextPageLink(), null, null, serviceCall, serviceCallback); } else { serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); } @@ -367,7 +355,7 @@ public Page nextPage(String nextPageLink) throws CloudException, IOExce PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = new PagingGetMultiplePagesWithOffsetNextOptions(); pagingGetMultiplePagesWithOffsetNextOptions.setMaxresults(pagingGetMultiplePagesWithOffsetOptions.getMaxresults()); pagingGetMultiplePagesWithOffsetNextOptions.setTimeout(pagingGetMultiplePagesWithOffsetOptions.getTimeout()); - return getMultiplePagesWithOffsetNext(nextPageLink, clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions).getBody(); + return getMultiplePagesWithOffsetNext(nextPageLink, null, null).getBody(); } }; return new ServiceResponse<>(result, response.getResponse()); @@ -407,7 +395,7 @@ public void onResponse(Call call, Response response) PagingGetMultiplePagesWithOffsetNextOptions pagingGetMultiplePagesWithOffsetNextOptions = new PagingGetMultiplePagesWithOffsetNextOptions(); pagingGetMultiplePagesWithOffsetNextOptions.setMaxresults(pagingGetMultiplePagesWithOffsetOptions.getMaxresults()); pagingGetMultiplePagesWithOffsetNextOptions.setTimeout(pagingGetMultiplePagesWithOffsetOptions.getTimeout()); - getMultiplePagesWithOffsetNextAsync(result.getBody().getNextPageLink(), clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions, serviceCall, serviceCallback); + getMultiplePagesWithOffsetNextAsync(result.getBody().getNextPageLink(), null, null, serviceCall, serviceCallback); } else { serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); } @@ -878,13 +866,7 @@ public ServiceResponse> getMultiplePagesNext(final String next final String clientRequestId = null; final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; Integer maxresults = null; - if (pagingGetMultiplePagesOptions != null) { - maxresults = pagingGetMultiplePagesOptions.getMaxresults(); - } Integer timeout = null; - if (pagingGetMultiplePagesOptions != null) { - timeout = pagingGetMultiplePagesOptions.getTimeout(); - } Call call = service.getMultiplePagesNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); return getMultiplePagesNextDelegate(call.execute()); } @@ -909,13 +891,7 @@ public ServiceCall getMultiplePagesNextAsync(final String nextPageLink, final Se final String clientRequestId = null; final PagingGetMultiplePagesOptions pagingGetMultiplePagesOptions = null; Integer maxresults = null; - if (pagingGetMultiplePagesOptions != null) { - maxresults = pagingGetMultiplePagesOptions.getMaxresults(); - } Integer timeout = null; - if (pagingGetMultiplePagesOptions != null) { - timeout = pagingGetMultiplePagesOptions.getTimeout(); - } Call call = service.getMultiplePagesNext(nextPageLink, clientRequestId, this.client.getAcceptLanguage(), maxresults, timeout); serviceCall.newCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @@ -926,7 +902,7 @@ public void onResponse(Call call, Response response) serviceCallback.load(result.getBody().getItems()); if (result.getBody().getNextPageLink() != null && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getMultiplePagesNextAsync(result.getBody().getNextPageLink(), clientRequestId, pagingGetMultiplePagesOptions, serviceCall, serviceCallback); + getMultiplePagesNextAsync(result.getBody().getNextPageLink(), null, null, serviceCall, serviceCallback); } else { serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); } @@ -1075,7 +1051,7 @@ public void onResponse(Call call, Response response) serviceCallback.load(result.getBody().getItems()); if (result.getBody().getNextPageLink() != null && serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) { - getMultiplePagesWithOffsetNextAsync(result.getBody().getNextPageLink(), clientRequestId, pagingGetMultiplePagesWithOffsetNextOptions, serviceCall, serviceCallback); + getMultiplePagesWithOffsetNextAsync(result.getBody().getNextPageLink(), null, null, serviceCall, serviceCallback); } else { serviceCallback.success(new ServiceResponse<>(serviceCallback.get(), result.getResponse())); } diff --git a/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj b/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj index cdd38079878f5..3047a09afadb8 100644 --- a/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj +++ b/AutoRest/Generators/Java/Azure.Java/AutoRest.Generator.Azure.Java.csproj @@ -66,6 +66,8 @@ AzureServiceClientRetrofitTemplate.cshtml + + diff --git a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeGenerator.cs b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeGenerator.cs index b4d8972515fd8..d17290e7a1b97 100644 --- a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeGenerator.cs +++ b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeGenerator.cs @@ -26,7 +26,7 @@ public class AzureJavaCodeGenerator : JavaCodeGenerator public AzureJavaCodeGenerator(Settings settings) : base(settings) { - _namer = new AzureJavaCodeNamer(); + _namer = new AzureJavaCodeNamer(settings.Namespace); IsSingleFileGenerationSupported = true; pageClasses = new Dictionary, string>(); } diff --git a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs index 66572a9409c37..9f73d3f513ea3 100644 --- a/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Azure.Java/AzureJavaCodeNamer.cs @@ -13,6 +13,11 @@ namespace Microsoft.Rest.Generator.Java.Azure { public class AzureJavaCodeNamer : JavaCodeNamer { + public AzureJavaCodeNamer(string nameSpace) + : base(nameSpace) + { + } + #region normalization private static string GetPagingSetting(Dictionary extensions, IDictionary, string> pageClasses, out string nextLinkName) @@ -61,7 +66,7 @@ public virtual void NormalizePaginatedMethods(ServiceClient serviceClient, IDict throw new ArgumentNullException("serviceClient"); } - var convertedTypes = new Dictionary(); + var convertedTypes = new Dictionary(); foreach (var method in serviceClient.Methods.Where(m => m.Extensions.ContainsKey(AzureExtensions.PageableExtension))) { @@ -76,76 +81,40 @@ public virtual void NormalizePaginatedMethods(ServiceClient serviceClient, IDict method.Extensions[AzureExtensions.PageableExtension] = null; } - foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeType).Select(s => s.Key).ToArray()) + foreach (var responseStatus in method.Responses.Where(r => r.Value.Body is CompositeTypeModel).Select(s => s.Key).ToArray()) { - var compositType = (CompositeType)method.Responses[responseStatus].Body; - var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceType) as SequenceType; + var compositType = (CompositeTypeModel)method.Responses[responseStatus].Body; + var sequenceType = compositType.Properties.Select(p => p.Type).FirstOrDefault(t => t is SequenceTypeModel) as SequenceTypeModel; // if the type is a wrapper over page-able response if (sequenceType != null) { - IType pagedResult; - pagedResult = new SequenceType + ITypeModel pagedResult; + pagedResult = new SequenceTypeModel { ElementType = sequenceType.ElementType, NameFormat = "List<{0}>" }; - convertedTypes[method.Responses[responseStatus].Body] = pagedResult; + convertedTypes[(ITypeModel)method.Responses[responseStatus].Body] = pagedResult; method.Responses[responseStatus] = new Response(pagedResult, method.Responses[responseStatus].Headers); } } - if (convertedTypes.ContainsKey(method.ReturnType.Body)) + if (convertedTypes.ContainsKey((ITypeModel) method.ReturnType.Body)) { - method.ReturnType = new Response(convertedTypes[method.ReturnType.Body], method.ReturnType.Headers); + method.ReturnType = new Response(convertedTypes[(ITypeModel)method.ReturnType.Body], method.ReturnType.Headers); } } - Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet(convertedTypes.Keys.Cast().Select(t => t.Name))); + Extensions.RemoveUnreferencedTypes(serviceClient, new HashSet(convertedTypes.Keys.Cast().Select(t => t.Name))); } - #endregion - - public override List ImportType(IType type, string ns) + protected override CompositeTypeModel NewCompositeTypeModel(CompositeType compositeType) { - List imports = new List(); - var compositeType = type as CompositeType; - if (compositeType != null && ns != null) - { - if (type.Name.Contains('<')) - { - imports.AddRange(compositeType.ParseGenericType().SelectMany(t => ImportType(t, ns))); - } - else if (compositeType.Extensions.ContainsKey(ExternalExtension) && - (bool)compositeType.Extensions[ExternalExtension]) - { - imports.Add(string.Join( - ".", - "com.microsoft.rest", - type.Name)); - } - else if (compositeType.IsResource()) - { - imports.Add(string.Join( - ".", - "com.microsoft.azure", - type.Name)); - } - else - { - imports.Add(string.Join( - ".", - ns.ToLower(CultureInfo.InvariantCulture), - "models", - type.Name)); - } - } - else - { - imports.AddRange(base.ImportType(type, ns)); - } - return imports; + return new AzureCompositeTypeModel(compositeType, _package); } + + #endregion } } \ No newline at end of file diff --git a/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs b/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs index 01fefddaea2f7..1af18a4d3b35f 100644 --- a/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs +++ b/AutoRest/Generators/Java/Azure.Java/GlobalSuppressions.cs @@ -39,3 +39,18 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "serviceCallback", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#CallbackDocumentation")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureJavaCodeNamer.#ImportType(Microsoft.Rest.Generator.ClientModel.IType,System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureJavaCodeNamer.#ImportType(Microsoft.Rest.Generator.ClientModel.IType,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureCompositeTypeModel.#_azureRuntimePackage")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureCompositeTypeModel.#.ctor(Microsoft.Rest.Generator.Java.CompositeTypeModel)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureJavaCodeGenerator.#.ctor(Microsoft.Rest.Generator.Settings)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureModelTemplateModel.#.ctor(Microsoft.Rest.Generator.ClientModel.CompositeType,Microsoft.Rest.Generator.ClientModel.ServiceClient)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "serviceCallback", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getItems", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "PagingBahavior", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getNextPageLink", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ListOperationCallback", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel.#TransformPagingGroupedParameter(Microsoft.Rest.Generator.Utilities.IndentedStringBuilder,Microsoft.Rest.Generator.Java.Azure.AzureMethodTemplateModel,System.Boolean)")] diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs index 4ea67d6a62153..993bb1f56af6a 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureMethodTemplateModel.cs @@ -10,12 +10,14 @@ using Microsoft.Rest.Generator.Java.Azure.Properties; using Microsoft.Rest.Generator.Java.TemplateModels; using Microsoft.Rest.Generator.Utilities; +using System.Net; namespace Microsoft.Rest.Generator.Java.Azure { public class AzureMethodTemplateModel : MethodTemplateModel { - private AzureJavaCodeNamer _namer; + private AzureResponseModel _returnTypeModel; + private Dictionary _responseModels; public AzureMethodTemplateModel(Method source, ServiceClient serviceClient) : base(source, serviceClient) @@ -27,20 +29,30 @@ public AzureMethodTemplateModel(Method source, ServiceClient serviceClient) this.ClientRequestIdString = AzureExtensions.GetClientRequestIdString(source); this.RequestIdString = AzureExtensions.GetRequestIdString(source); - this._namer = new AzureJavaCodeNamer(); + _returnTypeModel = new AzureResponseModel(ReturnType, this); + _responseModels = new Dictionary(); + Responses.ForEach(r => _responseModels.Add(r.Key, new AzureResponseModel(r.Value, this))); } - protected override JavaCodeNamer Namer + public string ClientRequestIdString { get; private set; } + + public string RequestIdString { get; private set; } + + public override ResponseModel ReturnTypeModel { get { - return _namer; + return _returnTypeModel; } } - public string ClientRequestIdString { get; private set; } - - public string RequestIdString { get; private set; } + public override Dictionary ResponseModels + { + get + { + return _responseModels; + } + } /// /// Returns true if method has x-ms-long-running-operation extension. @@ -112,14 +124,7 @@ public override string MethodParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant)) { - if (parameter.Type.IsPrimaryType(KnownPrimaryType.Stream)) - { - declarations.Add("final File " + parameter.Name); - } - else - { - declarations.Add("final " + parameter.Type.UserHandledType().ToString() + " " + parameter.Name); - } + declarations.Add("final " + parameter.ClientType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -138,7 +143,7 @@ public override string MethodRequiredParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired)) { - declarations.Add("final " + parameter.Type.UserHandledType().ToString() + " " + parameter.Name); + declarations.Add("final " + parameter.ClientType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -159,20 +164,19 @@ public override string MethodParameterDeclarationWithCallback } if (this.IsPagingOperation) { - SequenceType sequenceType = (SequenceType)ReturnType.Body; + SequenceTypeModel sequenceType = (SequenceTypeModel)ReturnType.Body; parameters += string.Format(CultureInfo.InvariantCulture, "final ListOperationCallback<{0}> serviceCallback", - sequenceType != null ? JavaCodeNamer.WrapPrimitiveType(sequenceType.ElementType).ToString() : "Void"); + sequenceType != null ? sequenceType.ElementTypeModel.InstanceType().Name : "Void"); } else if (this.IsPagingNextOperation) { - SequenceType sequenceType = (SequenceType)ReturnType.Body; + SequenceTypeModel sequenceType = (SequenceTypeModel)ReturnType.Body; parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCall serviceCall, final ListOperationCallback<{0}> serviceCallback", - sequenceType != null ? JavaCodeNamer.WrapPrimitiveType(sequenceType.ElementType).ToString() : "Void"); + sequenceType != null ? sequenceType.ElementTypeModel.InstanceType().Name : "Void"); } else { - parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", - ReturnType.Body != null ? JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).ToString() : "Void"); + parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", ReturnTypeModel.GenericBodyClientTypeString); } return parameters; @@ -190,20 +194,19 @@ public override string MethodRequiredParameterDeclarationWithCallback } if (this.IsPagingOperation) { - SequenceType sequenceType = (SequenceType)ReturnType.Body; + SequenceTypeModel sequenceType = (SequenceTypeModel)ReturnType.Body; parameters += string.Format(CultureInfo.InvariantCulture, "final ListOperationCallback<{0}> serviceCallback", - sequenceType != null ? JavaCodeNamer.WrapPrimitiveType(sequenceType.ElementType).ToString() : "Void"); + sequenceType != null ? sequenceType.ElementTypeModel.InstanceType().Name : "Void"); } else if (this.IsPagingNextOperation) { - SequenceType sequenceType = (SequenceType)ReturnType.Body; + SequenceTypeModel sequenceType = (SequenceTypeModel)ReturnType.Body; parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCall serviceCall, final ListOperationCallback<{0}> serviceCallback", - sequenceType != null ? JavaCodeNamer.WrapPrimitiveType(sequenceType.ElementType).ToString() : "Void"); + sequenceType != null ? sequenceType.ElementTypeModel.InstanceType().Name : "Void"); } else { - parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", - ReturnType.Body != null ? JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).ToString() : "Void"); + parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", ReturnTypeModel.GenericBodyClientTypeString); } return parameters; @@ -222,6 +225,18 @@ public override string MethodParameterInvocationWithCallback } } + public override string MethodRequiredParameterInvocationWithCallback + { + get + { + if (this.IsPagingOperation || this.IsPagingNextOperation) + { + return base.MethodRequiredParameterInvocationWithCallback.Replace("serviceCallback", "serviceCall, serviceCallback"); + } + return base.MethodRequiredParameterInvocationWithCallback; + } + } + public override IEnumerable Exceptions { get @@ -277,10 +292,10 @@ public string PollingResourceTypeArgs { get { - string args = "new TypeToken<" + GenericReturnTypeString + ">() { }.getType()"; + string args = "new TypeToken<" + ReturnTypeModel.GenericBodyClientTypeString + ">() { }.getType()"; if (ReturnType.Headers != null) { - args += ", " + ReturnType.Headers.Name + ".class"; + args += ", " + ReturnTypeModel.HeaderWireType + ".class"; } return args; } @@ -294,41 +309,41 @@ public override string ResponseBuilder } } - public override string ResponseGeneration + public override string ResponseGeneration(bool filterRequired = false) { - get + if (this.IsPagingOperation && !this.IsPagingNextOperation) { - if (this.IsPagingOperation && !this.IsPagingNextOperation) - { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0} response = {1}Delegate(call.execute());", - this.DelegateOperationResponseReturnTypeString, this.Name); + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0} response = {1}Delegate(call.execute());", + ReturnTypeModel.WireResponseTypeString, this.Name); - string invocation; - AzureMethodTemplateModel nextMethod = GetPagingNextMethod(out invocation); - - builder.AppendLine("PagedList<{0}> result = new PagedList<{0}>(response.getBody()) {{", ((SequenceType)ReturnType.Body).ElementType.Name) - .Indent().AppendLine("@Override") - .AppendLine("public Page<{0}> nextPage(String nextPageLink) throws CloudException, IOException {{", ((SequenceType)ReturnType.Body).ElementType.Name) - .Indent(); - TransformPagingGroupedParameter(builder, nextMethod); - builder.AppendLine("return {0}({1}).getBody();", invocation, nextMethod.MethodParameterInvocation) - .Outdent().AppendLine("}") - .Outdent().AppendLine("};"); - return builder.ToString(); - } - else if (this.IsPagingNonPollingOperation) - { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0}> response = {2}Delegate(call.execute());", - this.OperationResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); - builder.AppendLine("{0} result = response.getBody().getItems();", this.ReturnType.Body.Name); - return builder.ToString(); - } - else - { - return base.ResponseGeneration; - } + string invocation; + AzureMethodTemplateModel nextMethod = GetPagingNextMethod(out invocation); + + builder.AppendLine("PagedList<{0}> result = new PagedList<{0}>(response.getBody()) {{", ((SequenceType)ReturnType.Body).ElementType.Name) + .Indent().AppendLine("@Override") + .AppendLine("public Page<{0}> nextPage(String nextPageLink) throws {1}, IOException {{", + ((SequenceType)ReturnType.Body).ElementType.Name, + OperationExceptionTypeString) + .Indent(); + TransformPagingGroupedParameter(builder, nextMethod, filterRequired); + builder.AppendLine("return {0}({1}).getBody();", + invocation, filterRequired ? nextMethod.MethodRequiredParameterInvocation : nextMethod.MethodParameterInvocation) + .Outdent().AppendLine("}") + .Outdent().AppendLine("};"); + return builder.ToString(); + } + else if (this.IsPagingNonPollingOperation) + { + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0}> response = {2}Delegate(call.execute());", + ReturnTypeModel.ClientResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); + builder.AppendLine("{0} result = response.getBody().getItems();", this.ReturnType.Body.Name); + return builder.ToString(); + } + else + { + return base.ResponseGeneration(); } } @@ -341,12 +356,12 @@ public override string ReturnValue if (ReturnType.Headers != null) { return string.Format(CultureInfo.InvariantCulture, "new {0}<>(result, response.getHeaders(), response.getResponse())", - this.OperationResponseType); + ReturnTypeModel.ClientResponseType); } else { return string.Format(CultureInfo.InvariantCulture, "new {0}<>(result, response.getResponse())", - this.OperationResponseType); + ReturnTypeModel.ClientResponseType); } } else @@ -356,77 +371,74 @@ public override string ReturnValue } } - public override string SuccessCallback + public override string SuccessCallback(bool filterRequired = false) { - get + if (this.IsPagingOperation) { - if (this.IsPagingOperation) + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0} result = {1}Delegate(response);", + ReturnTypeModel.WireResponseTypeString, this.Name); + builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); + builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent() + .AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); + string invocation; + AzureMethodTemplateModel nextMethod = GetPagingNextMethod(out invocation, true); + TransformPagingGroupedParameter(builder, nextMethod, filterRequired); + var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}(result.getBody().getNextPageLink(), {1});", + invocation, + filterRequired ? nextMethod.MethodRequiredParameterInvocationWithCallback : nextMethod.MethodParameterInvocationWithCallback); + builder.AppendLine(nextCall.Replace(", nextPageLink", "")).Outdent(); + builder.AppendLine("} else {").Indent(); + if (ReturnType.Headers == null) { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0} result = {1}Delegate(response);", - this.DelegateOperationResponseReturnTypeString, this.Name); - builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); - builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent() - .AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); - string invocation; - AzureMethodTemplateModel nextMethod = GetPagingNextMethod(out invocation, true); - TransformPagingGroupedParameter(builder, nextMethod); - var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}(result.getBody().getNextPageLink(), {1});", - invocation, - nextMethod.MethodParameterInvocationWithCallback); - builder.AppendLine(nextCall.Replace(", nextPageLink", "")).Outdent(); - builder.AppendLine("} else {").Indent(); - if (ReturnType.Headers == null) - { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", this.OperationResponseType); - } - else - { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", this.OperationResponseType); - } - builder.Outdent().AppendLine("}"); - return builder.ToString(); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } - else if (this.IsPagingNextOperation) + else { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0} result = {1}Delegate(response);", this.DelegateOperationResponseReturnTypeString, this.Name); - builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); - builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent(); - builder.AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); - var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}Async(result.getBody().getNextPageLink(), {1});", - this.Name, - this.MethodParameterInvocationWithCallback); - builder.AppendLine(nextCall.Replace(", nextPageLink", "")).Outdent(); - builder.AppendLine("} else {").Indent(); - if (ReturnType.Headers == null) - { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", this.OperationResponseType); - } - else - { - builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", this.OperationResponseType); - } - builder.Outdent().AppendLine("}"); - return builder.ToString(); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); + } + builder.Outdent().AppendLine("}"); + return builder.ToString(); + } + else if (this.IsPagingNextOperation) + { + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0} result = {1}Delegate(response);", ReturnTypeModel.WireResponseTypeString, this.Name); + builder.AppendLine("serviceCallback.load(result.getBody().getItems());"); + builder.AppendLine("if (result.getBody().getNextPageLink() != null").Indent().Indent(); + builder.AppendLine("&& serviceCallback.progress(result.getBody().getItems()) == ListOperationCallback.PagingBahavior.CONTINUE) {").Outdent(); + var nextCall = string.Format(CultureInfo.InvariantCulture, "{0}Async(result.getBody().getNextPageLink(), {1});", + this.Name, + filterRequired ? MethodRequiredParameterInvocationWithCallback : MethodParameterInvocationWithCallback); + builder.AppendLine(nextCall.Replace(", nextPageLink", "")).Outdent(); + builder.AppendLine("} else {").Indent(); + if (ReturnType.Headers == null) + { + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } - else if (this.IsPagingNonPollingOperation) + else { - var builder = new IndentedStringBuilder(); - builder.AppendLine("{0}> result = {2}Delegate(response);", - this.OperationResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); - if (ReturnType.Headers == null) - { - builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getResponse()));", this.OperationResponseType); - } - else - { - builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", this.OperationResponseType); - } - return builder.ToString(); + builder.AppendLine("serviceCallback.success(new {0}<>(serviceCallback.get(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); + } + builder.Outdent().AppendLine("}"); + return builder.ToString(); + } + else if (this.IsPagingNonPollingOperation) + { + var builder = new IndentedStringBuilder(); + builder.AppendLine("{0}> result = {2}Delegate(response);", + ReturnTypeModel.ClientResponseType, ((SequenceType)ReturnType.Body).ElementType.Name, this.Name.ToCamelCase()); + if (ReturnType.Headers == null) + { + builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getResponse()));", ReturnTypeModel.ClientResponseType); } - return base.SuccessCallback; + else + { + builder.AppendLine("serviceCallback.success(new {0}<>(result.getBody().getItems(), result.getHeaders(), result.getResponse()));", ReturnTypeModel.ClientResponseType); + } + return builder.ToString(); } + return base.SuccessCallback(); } private AzureMethodTemplateModel GetPagingNextMethod(out string invocation, bool async = false) @@ -457,7 +469,7 @@ private AzureMethodTemplateModel GetPagingNextMethod(out string invocation, bool return methodModel; } - private void TransformPagingGroupedParameter(IndentedStringBuilder builder, AzureMethodTemplateModel nextMethod) + private void TransformPagingGroupedParameter(IndentedStringBuilder builder, AzureMethodTemplateModel nextMethod, bool filterRequired = false) { if (this.InputParameterTransformation.IsNullOrEmpty()) { @@ -469,6 +481,10 @@ private void TransformPagingGroupedParameter(IndentedStringBuilder builder, Azur { return; } + if (filterRequired && !nextGroupType.IsRequired) + { + return; + } if (!groupedType.IsRequired) { builder.AppendLine("{0} {1} = null;", nextGroupType.Name.ToPascalCase(), nextGroupType.Name.ToCamelCase()); @@ -490,57 +506,6 @@ private void TransformPagingGroupedParameter(IndentedStringBuilder builder, Azur } } - public override string DelegateReturnTypeString - { - get - { - if (this.IsPagingOperation || this.IsPagingNextOperation || this.IsPagingNonPollingOperation) - { - return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", ((SequenceType)ReturnType.Body).ElementType); - } - return base.DelegateReturnTypeString; - } - } - - public override string TypeTokenType(IType type) - { - SequenceType sequenceType = type as SequenceType; - if (sequenceType != null && (this.IsPagingOperation || this.IsPagingNextOperation || this.IsPagingNonPollingOperation)) - { - return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", sequenceType.ElementType); - } - return base.TypeTokenType(type); - } - - public override string GenericReturnTypeString - { - get - { - if (ReturnType.Body is SequenceType && this.IsPagingNextOperation) - { - return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", ((SequenceType)ReturnType.Body).ElementType); - } - else if (ReturnType.Body is SequenceType && this.IsPagingOperation) - { - return string.Format(CultureInfo.InvariantCulture, "PagedList<{0}>", ((SequenceType)ReturnType.Body).ElementType); - } - return base.GenericReturnTypeString; - } - } - - public override string CallbackGenericTypeString - { - get - { - if (ReturnType.Body is SequenceType && - (this.IsPagingOperation || this.IsPagingNextOperation)) - { - return JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).Name; - } - return base.CallbackGenericTypeString; - } - } - public override string ServiceCallConstruction { get @@ -586,7 +551,7 @@ public override List InterfaceImports imports.Add("com.microsoft.azure.ListOperationCallback"); imports.Add("com.microsoft.azure.PagedList"); imports.Remove("java.util.List"); - imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(new CompositeTypeModel(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); } return imports; } @@ -604,11 +569,11 @@ public override List ImplImports imports.Remove("com.microsoft.azure.AzureServiceResponseBuilder"); imports.Add("retrofit2.Callback"); this.Responses.Select(r => r.Value.Body).Concat(new IType[]{ DefaultResponse.Body }) - .SelectMany(t => t.ImportFrom(ServiceClient.Namespace, Namer)) - .Where(i => !this.Parameters.Any(p => p.Type.ImportFrom(ServiceClient.Namespace, Namer).Contains(i))) + .SelectMany(t => t.ImportSafe()) + .Where(i => !this.Parameters.Any(p => p.Type.ImportSafe().Contains(i))) .ForEach(i => imports.Remove(i)); // return type may have been removed as a side effect - imports.AddRange(this.ReturnType.Body.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(this.ReturnTypeModel.ImplImports); } if (this.IsPagingOperation || this.IsPagingNextOperation) { @@ -616,7 +581,7 @@ public override List ImplImports imports.Add("com.microsoft.azure.ListOperationCallback"); imports.Add("com.microsoft.azure.Page"); imports.Add("com.microsoft.azure.PagedList"); - imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(new CompositeTypeModel(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); } if (this.IsPagingNextOperation) { @@ -625,7 +590,7 @@ public override List ImplImports } if (this.IsPagingNonPollingOperation) { - imports.AddRange(new CompositeType { Name = "PageImpl" }.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(new CompositeTypeModel(ServiceClient.Namespace) { Name = "PageImpl" }.ImportSafe()); } return imports; } diff --git a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureModelTemplateModel.cs b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureModelTemplateModel.cs index e1c9e3e514e45..b1599747f1d74 100644 --- a/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureModelTemplateModel.cs +++ b/AutoRest/Generators/Java/Azure.Java/TemplateModels/AzureModelTemplateModel.cs @@ -18,7 +18,7 @@ public class AzureModelTemplateModel : ModelTemplateModel public AzureModelTemplateModel(CompositeType source, ServiceClient serviceClient) : base(source, serviceClient) { - _namer = new AzureJavaCodeNamer(); + _namer = new AzureJavaCodeNamer(serviceClient.Namespace); } protected override JavaCodeNamer Namer diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodGroupRetrofitTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodGroupRetrofitTemplate.cshtml index e80f2a2fc7dd3..0ff560088979c 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodGroupRetrofitTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodGroupRetrofitTemplate.cshtml @@ -31,6 +31,10 @@ else { @: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))") } +if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) +{ +@: @@Streaming +} @: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration); @EmptyLine } diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml index c35f3214704c2..f70fc9e4a3731 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureMethodTemplate.cshtml @@ -37,14 +37,14 @@ if (Model.LocalParameters.Any(p => !p.IsConstant && !p.IsRequired)) } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in @Model.OperationResponseType if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.ClientResponseType if successful. } else { -@: * @@return the @Model.OperationResponseType object if successful. +@: * @@return the @Model.ReturnTypeModel.ClientResponseType object if successful. } */ -public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { +public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { @foreach (var param in Model.RequiredNullableParameters) { @: if (@param.Name == null) { @@ -56,20 +56,20 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequi @: Validator.validate(@(param.Name)); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (!parameter.IsRequired) { -@: final @(parameter.Type.Name) @(parameter.Name) = null; +@: final @(parameter.WireType.Name) @(parameter.WireName) = @(parameter.WireType.DefaultValue(Model)); } if (parameter.IsConstant) { -@: final @(parameter.Type.Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } - @Model.BuildInputMappings() - - Response result = service.@(Model.Name)(@Model.MethodParameterApiInvocation).execute(); + @Model.BuildInputMappings(true) + @Model.RequiredParameterConversion + Response result = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation).execute(); return client.getAzureClient().@(Model.PollingMethod)(result, @Model.PollingResourceTypeArgs); } @EmptyLine @@ -106,20 +106,20 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (!parameter.IsRequired) { -@: final @(parameter.Type.Name) @(parameter.Name) = null; +@: final @(parameter.WireType.Name) @(parameter.WireName) = @(parameter.WireType.DefaultValue(Model)); } if (parameter.IsConstant) { -@: final @(parameter.Type.Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } - @Model.BuildInputMappings() - - Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); + @Model.BuildInputMappings(true) + @Model.RequiredParameterConversion + Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback<@Model.CallType>() { @@Override @@ -157,14 +157,14 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in @Model.OperationResponseType if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in @Model.ReturnTypeModel.ClientResponseType if successful. } else { -@: * @@return the @Model.OperationResponseType object if successful. +@: * @@return the @Model.ReturnTypeModel.ClientResponseType object if successful. } */ -public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { +public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { @foreach (var param in Model.RequiredNullableParameters) { @: if (@param.Name == null) { @@ -176,7 +176,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParam @: Validator.validate(@(param.Name)); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (parameter.IsConstant) { @@ -184,7 +184,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParam } } @Model.BuildInputMappings() - + @Model.ParameterConversion Response result = service.@(Model.Name)(@Model.MethodParameterApiInvocation).execute(); return client.getAzureClient().@(Model.PollingMethod)(result, @Model.PollingResourceTypeArgs); } @@ -222,7 +222,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallb @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (parameter.IsConstant) { @@ -230,7 +230,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallb } } @Model.BuildInputMappings() - + @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new Callback<@Model.CallType>() { diff --git a/AutoRest/Generators/Java/Azure.Java/Templates/AzureServiceClientRetrofitTemplate.cshtml b/AutoRest/Generators/Java/Azure.Java/Templates/AzureServiceClientRetrofitTemplate.cshtml index 8d643f9c62fb5..ce2a71a4e1727 100644 --- a/AutoRest/Generators/Java/Azure.Java/Templates/AzureServiceClientRetrofitTemplate.cshtml +++ b/AutoRest/Generators/Java/Azure.Java/Templates/AzureServiceClientRetrofitTemplate.cshtml @@ -31,6 +31,10 @@ else { @: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))") } +if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) +{ +@: @@Streaming +} @: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration); @EmptyLine } diff --git a/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureCompositeTypeModel.cs b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureCompositeTypeModel.cs new file mode 100644 index 0000000000000..b3d43ea2b8033 --- /dev/null +++ b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureCompositeTypeModel.cs @@ -0,0 +1,59 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using Microsoft.Rest.Generator.Azure; + +namespace Microsoft.Rest.Generator.Java.Azure +{ + public class AzureCompositeTypeModel : CompositeTypeModel + { + protected string _azureRuntimePackage = "com.microsoft.azure"; + + public AzureCompositeTypeModel(CompositeTypeModel javaCompositeType) + : this(javaCompositeType.Package.Replace(".models", "")) + { + this.LoadFrom(javaCompositeType); + } + + public AzureCompositeTypeModel(CompositeType compositeType, string package) + : this(package) + { + this.LoadFrom(compositeType); + } + + public AzureCompositeTypeModel(string package) + : base(package) + { + this._package = package; + } + + public override string Package + { + get + { + if (this.IsResource) { + return _azureRuntimePackage; + } + else + { + return base.Package; + } + } + } + + public bool IsResource + { + get + { + return (Name == "Resource" || Name == "SubResource") && + Extensions.ContainsKey(AzureExtensions.AzureResourceExtension) && + (bool)Extensions[AzureExtensions.AzureResourceExtension]; + } + } + } +} diff --git a/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs new file mode 100644 index 0000000000000..9195830021b21 --- /dev/null +++ b/AutoRest/Generators/Java/Azure.Java/TypeModels/AzureResponseModel.cs @@ -0,0 +1,78 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java.Azure +{ + public class AzureResponseModel : ResponseModel + { + private AzureMethodTemplateModel _method; + + public AzureResponseModel(Response response, AzureMethodTemplateModel method) + : base (response) + { + this._response = response; + this._method = method; + } + + public AzureResponseModel(ITypeModel body, ITypeModel headers, AzureMethodTemplateModel method) + : this(new Response(body, headers), method) + { + } + + public override string GenericBodyClientTypeString + { + get + { + if (BodyClientType is SequenceType && _method.IsPagingNextOperation) + { + return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", ((SequenceType)BodyClientType).ElementType); + } + else if (BodyClientType is SequenceType && _method.IsPagingOperation) + { + return string.Format(CultureInfo.InvariantCulture, "PagedList<{0}>", ((SequenceType)BodyClientType).ElementType); + } + return base.GenericBodyClientTypeString; + } + } + + public override string GenericBodyWireTypeString + { + get + { + SequenceTypeModel sequenceType = BodyWireType as SequenceTypeModel; + if (sequenceType != null && (_method.IsPagingOperation || _method.IsPagingNextOperation || _method.IsPagingNonPollingOperation)) + { + return string.Format(CultureInfo.InvariantCulture, "PageImpl<{0}>", sequenceType.ElementTypeModel.InstanceType()); + } + return base.GenericBodyWireTypeString; + } + } + public override string ClientCallbackTypeString + { + get + { + if (Body is SequenceType && + (_method.IsPagingOperation || _method.IsPagingNextOperation)) + { + return BodyClientType.InstanceType().Name; + } + return base.ClientCallbackTypeString; + } + } + + public override string GenericHeaderWireTypeString + { + get + { + return HeaderWireType.InstanceType().Name; + } + } + } +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java index 31770e6ff4800..e37c6c2725986 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperations.java @@ -10,7 +10,6 @@ package fixtures.bodyarray; -import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; @@ -766,9 +765,9 @@ public interface ArrayOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the List<DateTimeRfc1123> object wrapped in {@link ServiceResponse} if successful. + * @return the List<DateTime> object wrapped in {@link ServiceResponse} if successful. */ - ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException; + ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException; /** * Get date-time array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 Oct 1492 10:15:01 GMT']. @@ -777,7 +776,7 @@ public interface ArrayOperations { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; /** * Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 Oct 1492 10:15:01 GMT']. @@ -788,7 +787,7 @@ public interface ArrayOperations { * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ - ServiceResponse putDateTimeRfc1123Valid(List arrayBody) throws ErrorException, IOException, IllegalArgumentException; + ServiceResponse putDateTimeRfc1123Valid(List arrayBody) throws ErrorException, IOException, IllegalArgumentException; /** * Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 Oct 1492 10:15:01 GMT']. @@ -798,7 +797,7 @@ public interface ArrayOperations { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; + ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; /** * Get duration array value ['P123DT22H14M12.011S', 'P5DT1H0M0S']. @@ -896,6 +895,24 @@ public interface ArrayOperations { */ ServiceCall getByteInvalidNullAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + /** + * Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the List<String> object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse> getBase64Url() throws ErrorException, IOException; + + /** + * Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getBase64UrlAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + /** * Get array of complex type null value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java index 3833b47176fab..01f53ca7948f2 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyarray/ArrayOperationsImpl.java @@ -21,6 +21,7 @@ import fixtures.bodyarray.models.ErrorException; import fixtures.bodyarray.models.Product; import java.io.IOException; +import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; @@ -246,6 +247,10 @@ interface ArrayService { @GET("array/prim/byte/invalidnull") Call getByteInvalidNull(); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("array/prim/base64url/valid") + Call getBase64Url(); + @Headers("Content-Type: application/json; charset=utf-8") @GET("array/complex/null") Call getComplexNull(); @@ -2200,11 +2205,21 @@ private ServiceResponse> getDateTimeInvalidCharsDelegate(Response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the List<DateTimeRfc1123> object wrapped in {@link ServiceResponse} if successful. + * @return the List<DateTime> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException { + public ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException { Call call = service.getDateTimeRfc1123Valid(); - return getDateTimeRfc1123ValidDelegate(call.execute()); + ServiceResponse> response = getDateTimeRfc1123ValidDelegate(call.execute()); + List body = null; + if (response.getBody() != null) { + body = new ArrayList(); + for (DateTimeRfc1123 item : response.getBody()) { + DateTime value; + value = item.getDateTime(); + body.add(value); + } + } + return new ServiceResponse>(body, response.getResponse()); } /** @@ -2214,17 +2229,27 @@ public ServiceResponse> getDateTimeRfc1123Valid() throws E * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { + public ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Call call = service.getDateTimeRfc1123Valid(); final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { + call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override public void onResponse(Call call, Response response) { try { - serviceCallback.success(getDateTimeRfc1123ValidDelegate(response)); + ServiceResponse> result = getDateTimeRfc1123ValidDelegate(response); + List body = null; + if (result.getBody() != null) { + body = new ArrayList(); + for (DateTimeRfc1123 item : result.getBody()) { + DateTime value; + value = item.getDateTime(); + body.add(value); + } + } + serviceCallback.success(new ServiceResponse>(body, result.getResponse())); } catch (ErrorException | IOException exception) { serviceCallback.failure(exception); } @@ -2249,12 +2274,17 @@ private ServiceResponse> getDateTimeRfc1123ValidDelegate(R * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse putDateTimeRfc1123Valid(List arrayBody) throws ErrorException, IOException, IllegalArgumentException { + public ServiceResponse putDateTimeRfc1123Valid(List arrayBody) throws ErrorException, IOException, IllegalArgumentException { if (arrayBody == null) { throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null."); } Validator.validate(arrayBody); - Call call = service.putDateTimeRfc1123Valid(arrayBody); + List arrayBodyConverted = new ArrayList(); + for (DateTime item : arrayBody) { + DateTimeRfc1123 value = new DateTimeRfc1123(item); + arrayBodyConverted.add(value); + } + Call call = service.putDateTimeRfc1123Valid(arrayBodyConverted); return putDateTimeRfc1123ValidDelegate(call.execute()); } @@ -2266,7 +2296,7 @@ public ServiceResponse putDateTimeRfc1123Valid(List array * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { + public ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } @@ -2275,7 +2305,12 @@ public ServiceCall putDateTimeRfc1123ValidAsync(List arrayBody, return null; } Validator.validate(arrayBody, serviceCallback); - Call call = service.putDateTimeRfc1123Valid(arrayBody); + List arrayBodyConverted = new ArrayList(); + for (DateTime item : arrayBody) { + DateTimeRfc1123 value = new DateTimeRfc1123(item); + arrayBodyConverted.add(value); + } + Call call = service.putDateTimeRfc1123Valid(arrayBodyConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2546,6 +2581,51 @@ private ServiceResponse> getByteInvalidNullDelegate(Response> getBase64Url() throws ErrorException, IOException { + Call call = service.getBase64Url(); + return getBase64UrlDelegate(call.execute()); + } + + /** + * Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getBase64UrlAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getBase64Url(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback>(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getBase64UrlDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse> getBase64UrlDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder, ErrorException>(this.client.getMapperAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + /** * Get array of complex type null value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperations.java index 9630dce2205bf..15e2e11de56bd 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperations.java @@ -26,7 +26,7 @@ public interface BoolOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getTrue() throws ErrorException, IOException; @@ -64,7 +64,7 @@ public interface BoolOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getFalse() throws ErrorException, IOException; @@ -102,7 +102,7 @@ public interface BoolOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNull() throws ErrorException, IOException; @@ -120,7 +120,7 @@ public interface BoolOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalid() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperationsImpl.java index 756d569f7489a..5c3107666e0bc 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyboolean/BoolOperationsImpl.java @@ -84,7 +84,7 @@ interface BoolService { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getTrue() throws ErrorException, IOException { Call call = service.getTrue(); @@ -176,7 +176,7 @@ private ServiceResponse putTrueDelegate(Response response) t * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getFalse() throws ErrorException, IOException { Call call = service.getFalse(); @@ -268,7 +268,7 @@ private ServiceResponse putFalseDelegate(Response response) * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNull() throws ErrorException, IOException { Call call = service.getNull(); @@ -313,7 +313,7 @@ private ServiceResponse getNullDelegate(Response response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalid() throws ErrorException, IOException { Call call = service.getInvalid(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Datetimerfc1123Wrapper.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Datetimerfc1123Wrapper.java index 73e3b74ff6268..6136a56f86b1f 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Datetimerfc1123Wrapper.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Datetimerfc1123Wrapper.java @@ -33,6 +33,9 @@ public class Datetimerfc1123Wrapper { * @return the field value */ public DateTime getField() { + if (this.field == null) { + return null; + } return this.field.getDateTime(); } @@ -51,6 +54,9 @@ public void setField(DateTime field) { * @return the now value */ public DateTime getNow() { + if (this.now == null) { + return null; + } return this.now.getDateTime(); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Fish.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Fish.java index c820edca131a7..cdb598998e1c0 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Fish.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Fish.java @@ -10,8 +10,8 @@ package fixtures.bodycomplex.models; -import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonSubTypes; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Shark.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Shark.java index 9b0aa2344cf7f..2c1f2eaa58a37 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Shark.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodycomplex/models/Shark.java @@ -10,8 +10,8 @@ package fixtures.bodycomplex.models; -import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonSubTypes; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123Operations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123Operations.java index 5ce7050bfb070..9204bc950ba56 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123Operations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123Operations.java @@ -27,7 +27,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNull() throws ErrorException, IOException; @@ -45,7 +45,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalid() throws ErrorException, IOException; @@ -63,7 +63,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getOverflow() throws ErrorException, IOException; @@ -81,7 +81,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUnderflow() throws ErrorException, IOException; @@ -120,7 +120,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUtcLowercaseMaxDateTime() throws ErrorException, IOException; @@ -138,7 +138,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUtcUppercaseMaxDateTime() throws ErrorException, IOException; @@ -177,7 +177,7 @@ public interface Datetimerfc1123Operations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUtcMinDateTime() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java index ba0652d5a04de..aa6910fc4de5d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydatetimerfc1123/Datetimerfc1123OperationsImpl.java @@ -98,7 +98,7 @@ interface Datetimerfc1123Service { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNull() throws ErrorException, IOException { Call call = service.getNull(); @@ -153,7 +153,7 @@ private ServiceResponse getNullDelegate(Response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalid() throws ErrorException, IOException { Call call = service.getInvalid(); @@ -208,7 +208,7 @@ private ServiceResponse getInvalidDelegate(Response getOverflow() throws ErrorException, IOException { Call call = service.getOverflow(); @@ -263,7 +263,7 @@ private ServiceResponse getOverflowDelegate(Response getUnderflow() throws ErrorException, IOException { Call call = service.getUnderflow(); @@ -326,7 +326,8 @@ public ServiceResponse putUtcMaxDateTime(DateTime datetimeBody) throws Err if (datetimeBody == null) { throw new IllegalArgumentException("Parameter datetimeBody is required and cannot be null."); } - Call call = service.putUtcMaxDateTime(new DateTimeRfc1123(datetimeBody)); + DateTimeRfc1123 datetimeBodyConverted = new DateTimeRfc1123(datetimeBody); + Call call = service.putUtcMaxDateTime(datetimeBodyConverted); return putUtcMaxDateTimeDelegate(call.execute()); } @@ -346,7 +347,8 @@ public ServiceCall putUtcMaxDateTimeAsync(DateTime datetimeBody, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter datetimeBody is required and cannot be null.")); return null; } - Call call = service.putUtcMaxDateTime(new DateTimeRfc1123(datetimeBody)); + DateTimeRfc1123 datetimeBodyConverted = new DateTimeRfc1123(datetimeBody); + Call call = service.putUtcMaxDateTime(datetimeBodyConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -373,7 +375,7 @@ private ServiceResponse putUtcMaxDateTimeDelegate(Response r * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUtcLowercaseMaxDateTime() throws ErrorException, IOException { Call call = service.getUtcLowercaseMaxDateTime(); @@ -428,7 +430,7 @@ private ServiceResponse getUtcLowercaseMaxDateTimeDelegate(Resp * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUtcUppercaseMaxDateTime() throws ErrorException, IOException { Call call = service.getUtcUppercaseMaxDateTime(); @@ -491,7 +493,8 @@ public ServiceResponse putUtcMinDateTime(DateTime datetimeBody) throws Err if (datetimeBody == null) { throw new IllegalArgumentException("Parameter datetimeBody is required and cannot be null."); } - Call call = service.putUtcMinDateTime(new DateTimeRfc1123(datetimeBody)); + DateTimeRfc1123 datetimeBodyConverted = new DateTimeRfc1123(datetimeBody); + Call call = service.putUtcMinDateTime(datetimeBodyConverted); return putUtcMinDateTimeDelegate(call.execute()); } @@ -511,7 +514,8 @@ public ServiceCall putUtcMinDateTimeAsync(DateTime datetimeBody, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter datetimeBody is required and cannot be null.")); return null; } - Call call = service.putUtcMinDateTime(new DateTimeRfc1123(datetimeBody)); + DateTimeRfc1123 datetimeBodyConverted = new DateTimeRfc1123(datetimeBody); + Call call = service.putUtcMinDateTime(datetimeBodyConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -538,7 +542,7 @@ private ServiceResponse putUtcMinDateTimeDelegate(Response r * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the DateTimeRfc1123 object wrapped in {@link ServiceResponse} if successful. + * @return the DateTime object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUtcMinDateTime() throws ErrorException, IOException { Call call = service.getUtcMinDateTime(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java index e97d98320d4e8..1fd31d6edb98a 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperations.java @@ -10,7 +10,6 @@ package fixtures.bodydictionary; -import com.microsoft.rest.DateTimeRfc1123; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; @@ -762,9 +761,9 @@ public interface DictionaryOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Map<String, DateTimeRfc1123> object wrapped in {@link ServiceResponse} if successful. + * @return the Map<String, DateTime> object wrapped in {@link ServiceResponse} if successful. */ - ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException; + ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException; /** * Get date-time-rfc1123 dictionary value {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. @@ -773,7 +772,7 @@ public interface DictionaryOperations { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; /** * Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. @@ -784,7 +783,7 @@ public interface DictionaryOperations { * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ - ServiceResponse putDateTimeRfc1123Valid(Map arrayBody) throws ErrorException, IOException, IllegalArgumentException; + ServiceResponse putDateTimeRfc1123Valid(Map arrayBody) throws ErrorException, IOException, IllegalArgumentException; /** * Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. @@ -794,7 +793,7 @@ public interface DictionaryOperations { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall putDateTimeRfc1123ValidAsync(Map arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; + ServiceCall putDateTimeRfc1123ValidAsync(Map arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; /** * Get duration dictionary value {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}. @@ -892,6 +891,24 @@ public interface DictionaryOperations { */ ServiceCall getByteInvalidNullAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + /** + * Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test string", "2": "Lorem ipsum"}. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the Map<String, String> object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse> getBase64Url() throws ErrorException, IOException; + + /** + * Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test string", "2": "Lorem ipsum"}. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getBase64UrlAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException; + /** * Get dictionary of complex type null value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java index 7e1d89fe32734..0dfc895dfa5e3 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodydictionary/DictionaryOperationsImpl.java @@ -21,6 +21,7 @@ import fixtures.bodydictionary.models.ErrorException; import fixtures.bodydictionary.models.Widget; import java.io.IOException; +import java.util.HashMap; import java.util.List; import java.util.Map; import okhttp3.ResponseBody; @@ -245,6 +246,10 @@ interface DictionaryService { @GET("dictionary/prim/byte/invalidnull") Call getByteInvalidNull(); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("dictionary/prim/base64url/valid") + Call getBase64Url(); + @Headers("Content-Type: application/json; charset=utf-8") @GET("dictionary/complex/null") Call getComplexNull(); @@ -2187,11 +2192,21 @@ private ServiceResponse> getDateTimeInvalidCharsDelegate(R * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Map<String, DateTimeRfc1123> object wrapped in {@link ServiceResponse} if successful. + * @return the Map<String, DateTime> object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException { + public ServiceResponse> getDateTimeRfc1123Valid() throws ErrorException, IOException { Call call = service.getDateTimeRfc1123Valid(); - return getDateTimeRfc1123ValidDelegate(call.execute()); + ServiceResponse> response = getDateTimeRfc1123ValidDelegate(call.execute()); + Map body = null; + if (response.getBody() != null) { + body = new HashMap(); + for (Map.Entry entry : response.getBody().entrySet()) { + DateTime value; + value = entry.getValue().getDateTime(); + body.put(entry.getKey(), value); + } + } + return new ServiceResponse>(body, response.getResponse()); } /** @@ -2201,17 +2216,27 @@ public ServiceResponse> getDateTimeRfc1123Valid() t * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { + public ServiceCall getDateTimeRfc1123ValidAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Call call = service.getDateTimeRfc1123Valid(); final ServiceCall serviceCall = new ServiceCall(call); - call.enqueue(new ServiceResponseCallback>(serviceCallback) { + call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override public void onResponse(Call call, Response response) { try { - serviceCallback.success(getDateTimeRfc1123ValidDelegate(response)); + ServiceResponse> result = getDateTimeRfc1123ValidDelegate(response); + Map body = null; + if (result.getBody() != null) { + body = new HashMap(); + for (Map.Entry entry : result.getBody().entrySet()) { + DateTime value; + value = entry.getValue().getDateTime(); + body.put(entry.getKey(), value); + } + } + serviceCallback.success(new ServiceResponse>(body, result.getResponse())); } catch (ErrorException | IOException exception) { serviceCallback.failure(exception); } @@ -2236,12 +2261,17 @@ private ServiceResponse> getDateTimeRfc1123ValidDel * @throws IllegalArgumentException exception thrown from invalid parameters * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse putDateTimeRfc1123Valid(Map arrayBody) throws ErrorException, IOException, IllegalArgumentException { + public ServiceResponse putDateTimeRfc1123Valid(Map arrayBody) throws ErrorException, IOException, IllegalArgumentException { if (arrayBody == null) { throw new IllegalArgumentException("Parameter arrayBody is required and cannot be null."); } Validator.validate(arrayBody); - Call call = service.putDateTimeRfc1123Valid(arrayBody); + Map arrayBodyConverted = new HashMap(); + for (Map.Entry entry : arrayBody.entrySet()) { + DateTimeRfc1123 value = new DateTimeRfc1123(entry.getValue()); + arrayBodyConverted.put(entry.getKey(), value); + } + Call call = service.putDateTimeRfc1123Valid(arrayBodyConverted); return putDateTimeRfc1123ValidDelegate(call.execute()); } @@ -2253,7 +2283,7 @@ public ServiceResponse putDateTimeRfc1123Valid(Map arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { + public ServiceCall putDateTimeRfc1123ValidAsync(Map arrayBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } @@ -2262,7 +2292,12 @@ public ServiceCall putDateTimeRfc1123ValidAsync(Map arr return null; } Validator.validate(arrayBody, serviceCallback); - Call call = service.putDateTimeRfc1123Valid(arrayBody); + Map arrayBodyConverted = new HashMap(); + for (Map.Entry entry : arrayBody.entrySet()) { + DateTimeRfc1123 value = new DateTimeRfc1123(entry.getValue()); + arrayBodyConverted.put(entry.getKey(), value); + } + Call call = service.putDateTimeRfc1123Valid(arrayBodyConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2533,6 +2568,51 @@ private ServiceResponse> getByteInvalidNullDelegate(Response .build(response); } + /** + * Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test string", "2": "Lorem ipsum"}. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the Map<String, String> object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse> getBase64Url() throws ErrorException, IOException { + Call call = service.getBase64Url(); + return getBase64UrlDelegate(call.execute()); + } + + /** + * Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test string", "2": "Lorem ipsum"}. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getBase64UrlAsync(final ServiceCallback> serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getBase64Url(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback>(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getBase64UrlDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse> getBase64UrlDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder, ErrorException>(this.client.getMapperAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + /** * Get dictionary of complex type null value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/FilesOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/FilesOperationsImpl.java index 79dc46b022b25..06511befcedf1 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/FilesOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyfile/FilesOperationsImpl.java @@ -23,6 +23,7 @@ import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Headers; +import retrofit2.http.Streaming; import retrofit2.Response; import retrofit2.Retrofit; @@ -54,14 +55,17 @@ public FilesOperationsImpl(Retrofit retrofit, AutoRestSwaggerBATFileService clie interface FilesService { @Headers("Content-Type: application/json; charset=utf-8") @GET("files/stream/nonempty") + @Streaming Call getFile(); @Headers("Content-Type: application/json; charset=utf-8") @GET("files/stream/verylarge") + @Streaming Call getFileLarge(); @Headers("Content-Type: application/json; charset=utf-8") @GET("files/stream/empty") + @Streaming Call getEmptyFile(); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java index e71b309298dd4..94db4668feedc 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyformdata/FormdataOperationsImpl.java @@ -29,6 +29,7 @@ import retrofit2.http.Part; import retrofit2.http.POST; import retrofit2.http.PUT; +import retrofit2.http.Streaming; import retrofit2.Response; import retrofit2.Retrofit; @@ -60,10 +61,12 @@ public FormdataOperationsImpl(Retrofit retrofit, AutoRestSwaggerBATFormDataServi interface FormdataService { @Multipart @POST("formdata/stream/uploadfile") + @Streaming Call uploadFile(@Part("fileContent") RequestBody fileContent, @Part("fileName") String fileName); @Headers("Content-Type: application/octet-stream") @PUT("formdata/stream/uploadfile") + @Streaming Call uploadFileViaBody(@Body RequestBody fileContent); } @@ -85,7 +88,8 @@ public ServiceResponse uploadFile(byte[] fileContent, String fileNa if (fileName == null) { throw new IllegalArgumentException("Parameter fileName is required and cannot be null."); } - Call call = service.uploadFile(RequestBody.create(MediaType.parse("multipart/form-data"), fileContent), fileName); + RequestBody fileContentConverted = RequestBody.create(MediaType.parse("multipart/form-data"), fileContent); + Call call = service.uploadFile(fileContentConverted, fileName); return uploadFileDelegate(call.execute()); } @@ -110,7 +114,8 @@ public ServiceCall uploadFileAsync(byte[] fileContent, String fileName, final Se serviceCallback.failure(new IllegalArgumentException("Parameter fileName is required and cannot be null.")); return null; } - Call call = service.uploadFile(RequestBody.create(MediaType.parse("multipart/form-data"), fileContent), fileName); + RequestBody fileContentConverted = RequestBody.create(MediaType.parse("multipart/form-data"), fileContent); + Call call = service.uploadFile(fileContentConverted, fileName); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -145,7 +150,8 @@ public ServiceResponse uploadFileViaBody(byte[] fileContent) throws if (fileContent == null) { throw new IllegalArgumentException("Parameter fileContent is required and cannot be null."); } - Call call = service.uploadFileViaBody(RequestBody.create(MediaType.parse("application/octet-stream"), fileContent)); + RequestBody fileContentConverted = RequestBody.create(MediaType.parse("application/octet-stream"), fileContent); + Call call = service.uploadFileViaBody(fileContentConverted); return uploadFileViaBodyDelegate(call.execute()); } @@ -165,7 +171,8 @@ public ServiceCall uploadFileViaBodyAsync(byte[] fileContent, final ServiceCallb serviceCallback.failure(new IllegalArgumentException("Parameter fileContent is required and cannot be null.")); return null; } - Call call = service.uploadFileViaBody(RequestBody.create(MediaType.parse("application/octet-stream"), fileContent)); + RequestBody fileContentConverted = RequestBody.create(MediaType.parse("application/octet-stream"), fileContent); + Call call = service.uploadFileViaBody(fileContentConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java index aee8ce76f60ef..2f705c55d8129 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java @@ -26,7 +26,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNull() throws ErrorException, IOException; @@ -44,7 +44,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalid() throws ErrorException, IOException; @@ -62,7 +62,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getOverflowInt32() throws ErrorException, IOException; @@ -80,7 +80,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUnderflowInt32() throws ErrorException, IOException; @@ -98,7 +98,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Long object wrapped in {@link ServiceResponse} if successful. + * @return the long object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getOverflowInt64() throws ErrorException, IOException; @@ -116,7 +116,7 @@ public interface IntOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Long object wrapped in {@link ServiceResponse} if successful. + * @return the long object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getUnderflowInt64() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperationsImpl.java index 9074eb6cbbf90..8e9325c0caf42 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperationsImpl.java @@ -100,7 +100,7 @@ interface IntService { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNull() throws ErrorException, IOException { Call call = service.getNull(); @@ -145,7 +145,7 @@ private ServiceResponse getNullDelegate(Response response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalid() throws ErrorException, IOException { Call call = service.getInvalid(); @@ -190,7 +190,7 @@ private ServiceResponse getInvalidDelegate(Response respo * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getOverflowInt32() throws ErrorException, IOException { Call call = service.getOverflowInt32(); @@ -235,7 +235,7 @@ private ServiceResponse getOverflowInt32Delegate(Response * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Integer object wrapped in {@link ServiceResponse} if successful. + * @return the int object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUnderflowInt32() throws ErrorException, IOException { Call call = service.getUnderflowInt32(); @@ -280,7 +280,7 @@ private ServiceResponse getUnderflowInt32Delegate(Response getOverflowInt64() throws ErrorException, IOException { Call call = service.getOverflowInt64(); @@ -325,7 +325,7 @@ private ServiceResponse getOverflowInt64Delegate(Response re * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Long object wrapped in {@link ServiceResponse} if successful. + * @return the long object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getUnderflowInt64() throws ErrorException, IOException { Call call = service.getUnderflowInt64(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperations.java index ad3036ecd7b7b..d12b81146b25f 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperations.java @@ -27,7 +27,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNull() throws ErrorException, IOException; @@ -45,7 +45,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalidFloat() throws ErrorException, IOException; @@ -63,7 +63,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getInvalidDouble() throws ErrorException, IOException; @@ -119,7 +119,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getBigFloat() throws ErrorException, IOException; @@ -157,7 +157,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getBigDouble() throws ErrorException, IOException; @@ -195,7 +195,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getBigDoublePositiveDecimal() throws ErrorException, IOException; @@ -233,7 +233,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getBigDoubleNegativeDecimal() throws ErrorException, IOException; @@ -388,7 +388,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getSmallFloat() throws ErrorException, IOException; @@ -426,7 +426,7 @@ public interface NumberOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getSmallDouble() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperationsImpl.java index 4e73af2346ed6..63b156894fe55 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodynumber/NumberOperationsImpl.java @@ -157,7 +157,7 @@ interface NumberService { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNull() throws ErrorException, IOException { Call call = service.getNull(); @@ -202,7 +202,7 @@ private ServiceResponse getNullDelegate(Response response) * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalidFloat() throws ErrorException, IOException { Call call = service.getInvalidFloat(); @@ -247,7 +247,7 @@ private ServiceResponse getInvalidFloatDelegate(Response r * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getInvalidDouble() throws ErrorException, IOException { Call call = service.getInvalidDouble(); @@ -384,7 +384,7 @@ private ServiceResponse putBigFloatDelegate(Response respons * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getBigFloat() throws ErrorException, IOException { Call call = service.getBigFloat(); @@ -476,7 +476,7 @@ private ServiceResponse putBigDoubleDelegate(Response respon * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getBigDouble() throws ErrorException, IOException { Call call = service.getBigDouble(); @@ -568,7 +568,7 @@ private ServiceResponse putBigDoublePositiveDecimalDelegate(Response getBigDoublePositiveDecimal() throws ErrorException, IOException { Call call = service.getBigDoublePositiveDecimal(); @@ -660,7 +660,7 @@ private ServiceResponse putBigDoubleNegativeDecimalDelegate(Response getBigDoubleNegativeDecimal() throws ErrorException, IOException { Call call = service.getBigDoubleNegativeDecimal(); @@ -1052,7 +1052,7 @@ private ServiceResponse putSmallFloatDelegate(Response respo * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getSmallFloat() throws ErrorException, IOException { Call call = service.getSmallFloat(); @@ -1144,7 +1144,7 @@ private ServiceResponse putSmallDoubleDelegate(Response resp * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Double object wrapped in {@link ServiceResponse} if successful. + * @return the double object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getSmallDouble() throws ErrorException, IOException { Call call = service.getSmallDouble(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperations.java index 6256d70621307..0107642a2747d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperations.java @@ -211,4 +211,79 @@ public interface StringOperations { */ ServiceCall getNotProvidedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Get value that is base64 encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse getBase64Encoded() throws ErrorException, IOException; + + /** + * Get value that is base64 encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getBase64EncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Get value that is base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse getBase64UrlEncoded() throws ErrorException, IOException; + + /** + * Get value that is base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getBase64UrlEncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Put value that is base64url encoded. + * + * @param stringBody the String value + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse putBase64UrlEncoded(String stringBody) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Put value that is base64url encoded. + * + * @param stringBody the String value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall putBase64UrlEncodedAsync(String stringBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Get null value that is expected to be base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse getNullBase64UrlEncoded() throws ErrorException, IOException; + + /** + * Get null value that is expected to be base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getNullBase64UrlEncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java index d4b1368b107ae..c4cb06e5903fe 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/StringOperationsImpl.java @@ -89,6 +89,22 @@ interface StringService { @GET("string/notProvided") Call getNotProvided(); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("string/base64Encoding") + Call getBase64Encoded(); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("string/base64UrlEncoding") + Call getBase64UrlEncoded(); + + @Headers("Content-Type: application/json; charset=utf-8") + @PUT("string/base64UrlEncoding") + Call putBase64UrlEncoded(@Body String stringBody); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("string/nullBase64UrlEncoding") + Call getNullBase64UrlEncoded(); + } /** @@ -568,4 +584,194 @@ private ServiceResponse getNotProvidedDelegate(Response re .build(response); } + /** + * Get value that is base64 encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse getBase64Encoded() throws ErrorException, IOException { + Call call = service.getBase64Encoded(); + return getBase64EncodedDelegate(call.execute()); + } + + /** + * Get value that is base64 encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getBase64EncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getBase64Encoded(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getBase64EncodedDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getBase64EncodedDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Get value that is base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse getBase64UrlEncoded() throws ErrorException, IOException { + Call call = service.getBase64UrlEncoded(); + return getBase64UrlEncodedDelegate(call.execute()); + } + + /** + * Get value that is base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getBase64UrlEncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getBase64UrlEncoded(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getBase64UrlEncodedDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getBase64UrlEncodedDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Put value that is base64url encoded. + * + * @param stringBody the String value + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse putBase64UrlEncoded(String stringBody) throws ErrorException, IOException, IllegalArgumentException { + if (stringBody == null) { + throw new IllegalArgumentException("Parameter stringBody is required and cannot be null."); + } + Call call = service.putBase64UrlEncoded(stringBody); + return putBase64UrlEncodedDelegate(call.execute()); + } + + /** + * Put value that is base64url encoded. + * + * @param stringBody the String value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall putBase64UrlEncodedAsync(String stringBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (stringBody == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter stringBody is required and cannot be null.")); + return null; + } + Call call = service.putBase64UrlEncoded(stringBody); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(putBase64UrlEncodedDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse putBase64UrlEncodedDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Get null value that is expected to be base64url encoded. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the String object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse getNullBase64UrlEncoded() throws ErrorException, IOException { + Call call = service.getNullBase64UrlEncoded(); + return getNullBase64UrlEncodedDelegate(call.execute()); + } + + /** + * Get null value that is expected to be base64url encoded. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getNullBase64UrlEncodedAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getNullBase64UrlEncoded(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getNullBase64UrlEncodedDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getNullBase64UrlEncodedDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/models/Colors.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/models/Colors.java index 920bea2c2474c..d87da877c4845 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/models/Colors.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodystring/models/Colors.java @@ -59,4 +59,9 @@ public static Colors fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClient.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClient.java new file mode 100644 index 0000000000000..7c5bb29be05d4 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClient.java @@ -0,0 +1,86 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions; + +import java.util.List; +import okhttp3.Interceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import com.microsoft.rest.AutoRestBaseUrl; +import com.microsoft.rest.serializer.JacksonMapperAdapter; + +/** + * The interface for AutoRestParameterizedCustomHostTestClient class. + */ +public interface AutoRestParameterizedCustomHostTestClient { + /** + * Gets the URL used as the base for all cloud service requests. + * + * @return the BaseUrl object. + */ + AutoRestBaseUrl getBaseUrl(); + + /** + * Gets the list of interceptors the OkHttp client will execute. + * + * @return the list of interceptors. + */ + List getClientInterceptors(); + + /** + * Sets the logging level for OkHttp client. + * + * @param logLevel the logging level enum. + */ + void setLogLevel(Level logLevel); + + /** + * Gets the adapter for {@link com.fasterxml.jackson.databind.ObjectMapper} for serialization + * and deserialization operations.. + * + * @return the adapter. + */ + JacksonMapperAdapter getMapperAdapter(); + + /** + * Gets The subscription id with value 'test12'.. + * + * @return the subscriptionId value. + */ + String getSubscriptionId(); + + /** + * Sets The subscription id with value 'test12'.. + * + * @param subscriptionId the subscriptionId value. + */ + void setSubscriptionId(String subscriptionId); + + /** + * Gets A string value that is used as a global part of the parameterized host. Default value 'host'.. + * + * @return the dnsSuffix value. + */ + String getDnsSuffix(); + + /** + * Sets A string value that is used as a global part of the parameterized host. Default value 'host'.. + * + * @param dnsSuffix the dnsSuffix value. + */ + void setDnsSuffix(String dnsSuffix); + + /** + * Gets the PathsOperations object to access its operations. + * @return the PathsOperations object. + */ + PathsOperations getPathsOperations(); + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClientImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClientImpl.java new file mode 100644 index 0000000000000..ad9fe946dc423 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClientImpl.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions; + +import com.microsoft.rest.ServiceClient; +import com.microsoft.rest.AutoRestBaseUrl; +import okhttp3.OkHttpClient; +import retrofit2.Retrofit; + +/** + * Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + */ +public final class AutoRestParameterizedCustomHostTestClientImpl extends ServiceClient implements AutoRestParameterizedCustomHostTestClient { + /** + * The URL used as the base for all cloud service requests. + */ + private final AutoRestBaseUrl baseUrl; + + /** + * Gets the URL used as the base for all cloud service requests. + * + * @return The BaseUrl value. + */ + public AutoRestBaseUrl getBaseUrl() { + return this.baseUrl; + } + + /** The subscription id with value 'test12'. */ + private String subscriptionId; + + /** + * Gets The subscription id with value 'test12'. + * + * @return the subscriptionId value. + */ + public String getSubscriptionId() { + return this.subscriptionId; + } + + /** + * Sets The subscription id with value 'test12'. + * + * @param subscriptionId the subscriptionId value. + */ + public void setSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + } + + /** A string value that is used as a global part of the parameterized host. Default value 'host'. */ + private String dnsSuffix; + + /** + * Gets A string value that is used as a global part of the parameterized host. Default value 'host'. + * + * @return the dnsSuffix value. + */ + public String getDnsSuffix() { + return this.dnsSuffix; + } + + /** + * Sets A string value that is used as a global part of the parameterized host. Default value 'host'. + * + * @param dnsSuffix the dnsSuffix value. + */ + public void setDnsSuffix(String dnsSuffix) { + this.dnsSuffix = dnsSuffix; + } + + /** + * Gets the PathsOperations object to access its operations. + * @return the PathsOperations object. + */ + public PathsOperations getPathsOperations() { + return new PathsOperationsImpl(this.retrofitBuilder.client(clientBuilder.build()).build(), this); + } + + /** + * Initializes an instance of AutoRestParameterizedCustomHostTestClient client. + */ + public AutoRestParameterizedCustomHostTestClientImpl() { + this("{vault}{secret}{dnsSuffix}"); + } + + /** + * Initializes an instance of AutoRestParameterizedCustomHostTestClient client. + * + * @param baseUrl the base URL of the host + */ + private AutoRestParameterizedCustomHostTestClientImpl(String baseUrl) { + super(); + this.baseUrl = new AutoRestBaseUrl(baseUrl); + initialize(); + } + + /** + * Initializes an instance of AutoRestParameterizedCustomHostTestClient client. + * + * @param clientBuilder the builder for building up an {@link OkHttpClient} + * @param retrofitBuilder the builder for building up a {@link Retrofit} + */ + public AutoRestParameterizedCustomHostTestClientImpl(OkHttpClient.Builder clientBuilder, Retrofit.Builder retrofitBuilder) { + super(clientBuilder, retrofitBuilder); + this.baseUrl = new AutoRestBaseUrl("{vault}{secret}{dnsSuffix}"); + initialize(); + } + + @Override + protected void initialize() { + super.initialize(); + this.retrofitBuilder.baseUrl(baseUrl); + } +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperations.java new file mode 100644 index 0000000000000..6273f3426d73c --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperations.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions; + +import com.microsoft.rest.ServiceCall; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceResponse; +import fixtures.custombaseurimoreoptions.models.ErrorException; +import java.io.IOException; + +/** + * An instance of this class provides access to all the operations defined + * in PathsOperations. + */ +public interface PathsOperations { + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse getEmpty(String vault, String secret, String keyName) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getEmptyAsync(String vault, String secret, String keyName, final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param keyVersion The key version. Default value 'v1'. + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse getEmpty(String vault, String secret, String keyName, String keyVersion) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param keyVersion The key version. Default value 'v1'. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall getEmptyAsync(String vault, String secret, String keyName, String keyVersion, final ServiceCallback serviceCallback) throws IllegalArgumentException; + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperationsImpl.java new file mode 100644 index 0000000000000..13994720257bd --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperationsImpl.java @@ -0,0 +1,245 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions; + +import com.google.common.reflect.TypeToken; +import com.microsoft.rest.ServiceCall; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.ServiceResponseBuilder; +import com.microsoft.rest.ServiceResponseCallback; +import fixtures.custombaseurimoreoptions.models.ErrorException; +import java.io.IOException; +import okhttp3.ResponseBody; +import retrofit2.Call; +import retrofit2.http.GET; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.Response; +import retrofit2.Retrofit; + +/** + * An instance of this class provides access to all the operations defined + * in PathsOperations. + */ +public final class PathsOperationsImpl implements PathsOperations { + /** The Retrofit service to perform REST calls. */ + private PathsService service; + /** The service client containing this operation class. */ + private AutoRestParameterizedCustomHostTestClient client; + + /** + * Initializes an instance of PathsOperations. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public PathsOperationsImpl(Retrofit retrofit, AutoRestParameterizedCustomHostTestClient client) { + this.service = retrofit.create(PathsService.class); + this.client = client; + } + + /** + * The interface defining all the services for PathsOperations to be + * used by Retrofit to perform actually REST calls. + */ + interface PathsService { + @Headers("Content-Type: application/json; charset=utf-8") + @GET("customuri/{subscriptionId}/{keyName}") + Call getEmpty(@Path("keyName") String keyName, @Path("subscriptionId") String subscriptionId, @Query("keyVersion") String keyVersion); + + } + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse getEmpty(String vault, String secret, String keyName) throws ErrorException, IOException, IllegalArgumentException { + if (vault == null) { + throw new IllegalArgumentException("Parameter vault is required and cannot be null."); + } + if (secret == null) { + throw new IllegalArgumentException("Parameter secret is required and cannot be null."); + } + if (this.client.getDnsSuffix() == null) { + throw new IllegalArgumentException("Parameter this.client.getDnsSuffix() is required and cannot be null."); + } + if (keyName == null) { + throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); + } + if (this.client.getSubscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null."); + } + final String keyVersion = null; + this.client.getBaseUrl().set("{vault}", vault); + this.client.getBaseUrl().set("{secret}", secret); + this.client.getBaseUrl().set("{dnsSuffix}", this.client.getDnsSuffix()); + Call call = service.getEmpty(keyName, this.client.getSubscriptionId(), keyVersion); + return getEmptyDelegate(call.execute()); + } + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getEmptyAsync(String vault, String secret, String keyName, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (vault == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter vault is required and cannot be null.")); + return null; + } + if (secret == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter secret is required and cannot be null.")); + return null; + } + if (this.client.getDnsSuffix() == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getDnsSuffix() is required and cannot be null.")); + return null; + } + if (keyName == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter keyName is required and cannot be null.")); + return null; + } + if (this.client.getSubscriptionId() == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null.")); + return null; + } + final String keyVersion = null; + this.client.getBaseUrl().set("{vault}", vault); + this.client.getBaseUrl().set("{secret}", secret); + this.client.getBaseUrl().set("{dnsSuffix}", this.client.getDnsSuffix()); + Call call = service.getEmpty(keyName, this.client.getSubscriptionId(), keyVersion); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getEmptyDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param keyVersion The key version. Default value 'v1'. + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse getEmpty(String vault, String secret, String keyName, String keyVersion) throws ErrorException, IOException, IllegalArgumentException { + if (vault == null) { + throw new IllegalArgumentException("Parameter vault is required and cannot be null."); + } + if (secret == null) { + throw new IllegalArgumentException("Parameter secret is required and cannot be null."); + } + if (this.client.getDnsSuffix() == null) { + throw new IllegalArgumentException("Parameter this.client.getDnsSuffix() is required and cannot be null."); + } + if (keyName == null) { + throw new IllegalArgumentException("Parameter keyName is required and cannot be null."); + } + if (this.client.getSubscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null."); + } + this.client.getBaseUrl().set("{vault}", vault); + this.client.getBaseUrl().set("{secret}", secret); + this.client.getBaseUrl().set("{dnsSuffix}", this.client.getDnsSuffix()); + Call call = service.getEmpty(keyName, this.client.getSubscriptionId(), keyVersion); + return getEmptyDelegate(call.execute()); + } + + /** + * Get a 200 to test a valid base uri. + * + * @param vault The vault name, e.g. https://myvault + * @param secret Secret value. + * @param keyName The key name with value 'key1'. + * @param keyVersion The key version. Default value 'v1'. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall getEmptyAsync(String vault, String secret, String keyName, String keyVersion, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (vault == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter vault is required and cannot be null.")); + return null; + } + if (secret == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter secret is required and cannot be null.")); + return null; + } + if (this.client.getDnsSuffix() == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getDnsSuffix() is required and cannot be null.")); + return null; + } + if (keyName == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter keyName is required and cannot be null.")); + return null; + } + if (this.client.getSubscriptionId() == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null.")); + return null; + } + this.client.getBaseUrl().set("{vault}", vault); + this.client.getBaseUrl().set("{secret}", secret); + this.client.getBaseUrl().set("{dnsSuffix}", this.client.getDnsSuffix()); + Call call = service.getEmpty(keyName, this.client.getSubscriptionId(), keyVersion); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getEmptyDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getEmptyDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/Error.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/Error.java new file mode 100644 index 0000000000000..73232cf4ed434 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/Error.java @@ -0,0 +1,64 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions.models; + + +/** + * The Error model. + */ +public class Error { + /** + * The status property. + */ + private Integer status; + + /** + * The message property. + */ + private String message; + + /** + * Get the status value. + * + * @return the status value + */ + public Integer getStatus() { + return this.status; + } + + /** + * Set the status value. + * + * @param status the status value to set + */ + public void setStatus(Integer status) { + this.status = status; + } + + /** + * Get the message value. + * + * @return the message value + */ + public String getMessage() { + return this.message; + } + + /** + * Set the message value. + * + * @param message the message value to set + */ + public void setMessage(String message) { + this.message = message; + } + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/ErrorException.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/ErrorException.java new file mode 100644 index 0000000000000..0c4458e200dac --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/ErrorException.java @@ -0,0 +1,89 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.custombaseurimoreoptions.models; + +import com.microsoft.rest.AutoRestException; +import retrofit2.Response; + +/** + * Exception thrown for an invalid response with Error information. + */ +public class ErrorException extends AutoRestException { + /** + * Information about the associated HTTP response. + */ + private Response response; + /** + * The actual response body. + */ + private Error body; + /** + * Initializes a new instance of the ErrorException class. + */ + public ErrorException() { } + /** + * Initializes a new instance of the ErrorException class. + * + * @param message The exception message. + */ + public ErrorException(final String message) { + super(message); + } + /** + * Initializes a new instance of the ErrorException class. + * + * @param message the exception message + * @param cause exception that caused this exception to occur + */ + public ErrorException(final String message, final Throwable cause) { + super(message, cause); + } + /** + * Initializes a new instance of the ErrorException class. + * + * @param cause exception that caused this exception to occur + */ + public ErrorException(final Throwable cause) { + super(cause); + } + /** + * Gets information about the associated HTTP response. + * + * @return the HTTP response + */ + public Response getResponse() { + return response; + } + /** + * Gets the HTTP response body. + * + * @return the response body + */ + public Error getBody() { + return body; + } + /** + * Sets the HTTP response. + * + * @param response the HTTP response + */ + public void setResponse(Response response) { + this.response = response; + } + /** + * Sets the HTTP response body. + * + * @param body the response body + */ + public void setBody(Error body) { + this.body = body; + } +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/package-info.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/package-info.java new file mode 100644 index 0000000000000..b5c9a91ec97d8 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/package-info.java @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +/** + * This package contains the model classes for AutoRestParameterizedCustomHostTestClient. + * Test Infrastructure for AutoRest. + */ +package fixtures.custombaseurimoreoptions.models; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/package-info.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/package-info.java new file mode 100644 index 0000000000000..a6434083eb1c5 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/package-info.java @@ -0,0 +1,13 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. +// Changes may cause incorrect behavior and will be lost if the code is +// regenerated. + +/** + * This package contains the classes for AutoRestParameterizedCustomHostTestClient. + * Test Infrastructure for AutoRest. + */ +package fixtures.custombaseurimoreoptions; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java index 80c9db76accc4..fb0c9f8b0db51 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/HeaderOperationsImpl.java @@ -139,7 +139,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/date") - Call paramDate(@Header("scenario") String scenario, @Header("value") String value); + Call paramDate(@Header("scenario") String scenario, @Header("value") LocalDate value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/date") @@ -147,7 +147,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/datetime") - Call paramDatetime(@Header("scenario") String scenario, @Header("value") String value); + Call paramDatetime(@Header("scenario") String scenario, @Header("value") DateTime value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/datetime") @@ -179,7 +179,7 @@ interface HeaderService { @Headers("Content-Type: application/json; charset=utf-8") @POST("header/param/prim/enum") - Call paramEnum(@Header("scenario") String scenario, @Header("value") String value); + Call paramEnum(@Header("scenario") String scenario, @Header("value") GreyscaleColors value); @Headers("Content-Type: application/json; charset=utf-8") @POST("header/response/prim/enum") @@ -1130,7 +1130,7 @@ public ServiceResponse paramDate(String scenario, LocalDate value) throws if (value == null) { throw new IllegalArgumentException("Parameter value is required and cannot be null."); } - Call call = service.paramDate(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramDate(scenario, value); return paramDateDelegate(call.execute()); } @@ -1155,7 +1155,7 @@ public ServiceCall paramDateAsync(String scenario, LocalDate value, final Servic serviceCallback.failure(new IllegalArgumentException("Parameter value is required and cannot be null.")); return null; } - Call call = service.paramDate(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramDate(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1249,7 +1249,7 @@ public ServiceResponse paramDatetime(String scenario, DateTime value) thro if (value == null) { throw new IllegalArgumentException("Parameter value is required and cannot be null."); } - Call call = service.paramDatetime(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramDatetime(scenario, value); return paramDatetimeDelegate(call.execute()); } @@ -1274,7 +1274,7 @@ public ServiceCall paramDatetimeAsync(String scenario, DateTime value, final Ser serviceCallback.failure(new IllegalArgumentException("Parameter value is required and cannot be null.")); return null; } - Call call = service.paramDatetime(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramDatetime(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1364,8 +1364,8 @@ public ServiceResponse paramDatetimeRfc1123(String scenario) throws ErrorE if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - final DateTime value = null; - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + final DateTimeRfc1123 valueConverted = null; + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1385,8 +1385,8 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, final ServiceCallb serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - final DateTime value = null; - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + final DateTimeRfc1123 valueConverted = null; + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1415,7 +1415,11 @@ public ServiceResponse paramDatetimeRfc1123(String scenario, DateTime valu if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + DateTimeRfc1123 valueConverted = null; + if (value != null) { + valueConverted = new DateTimeRfc1123(value); + } + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); return paramDatetimeRfc1123Delegate(call.execute()); } @@ -1436,7 +1440,11 @@ public ServiceCall paramDatetimeRfc1123Async(String scenario, DateTime value, fi serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - Call call = service.paramDatetimeRfc1123(scenario, new DateTimeRfc1123(value)); + DateTimeRfc1123 valueConverted = null; + if (value != null) { + valueConverted = new DateTimeRfc1123(value); + } + Call call = service.paramDatetimeRfc1123(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1649,7 +1657,8 @@ public ServiceResponse paramByte(String scenario, byte[] value) throws Err if (value == null) { throw new IllegalArgumentException("Parameter value is required and cannot be null."); } - Call call = service.paramByte(scenario, Base64.encodeBase64String(value)); + String valueConverted = Base64.encodeBase64String(value); + Call call = service.paramByte(scenario, valueConverted); return paramByteDelegate(call.execute()); } @@ -1674,7 +1683,8 @@ public ServiceCall paramByteAsync(String scenario, byte[] value, final ServiceCa serviceCallback.failure(new IllegalArgumentException("Parameter value is required and cannot be null.")); return null; } - Call call = service.paramByte(scenario, Base64.encodeBase64String(value)); + String valueConverted = Base64.encodeBase64String(value); + Call call = service.paramByte(scenario, valueConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1765,7 +1775,7 @@ public ServiceResponse paramEnum(String scenario) throws ErrorException, I throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } final GreyscaleColors value = null; - Call call = service.paramEnum(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramEnum(scenario, value); return paramEnumDelegate(call.execute()); } @@ -1786,7 +1796,7 @@ public ServiceCall paramEnumAsync(String scenario, final ServiceCallback s return null; } final GreyscaleColors value = null; - Call call = service.paramEnum(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramEnum(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1815,7 +1825,7 @@ public ServiceResponse paramEnum(String scenario, GreyscaleColors value) t if (scenario == null) { throw new IllegalArgumentException("Parameter scenario is required and cannot be null."); } - Call call = service.paramEnum(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramEnum(scenario, value); return paramEnumDelegate(call.execute()); } @@ -1836,7 +1846,7 @@ public ServiceCall paramEnumAsync(String scenario, GreyscaleColors value, final serviceCallback.failure(new IllegalArgumentException("Parameter scenario is required and cannot be null.")); return null; } - Call call = service.paramEnum(scenario, this.client.getMapperAdapter().serializeRaw(value)); + Call call = service.paramEnum(scenario, value); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/GreyscaleColors.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/GreyscaleColors.java index 957fc5d82c1bc..c69abd1e6071f 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/GreyscaleColors.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/GreyscaleColors.java @@ -59,4 +59,9 @@ public static GreyscaleColors fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java index 627af266e6942..9728eb3f4d64a 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/header/models/HeaderResponseDatetimeRfc1123Headers.java @@ -29,6 +29,9 @@ public class HeaderResponseDatetimeRfc1123Headers { * @return the value value */ public DateTime getValue() { + if (this.value == null) { + return null; + } return this.value.getDateTime(); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperations.java index 2b77460dcacfb..b5db0e90d14de 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperations.java @@ -27,7 +27,7 @@ public interface HttpFailureOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getEmptyError() throws ErrorException, IOException; @@ -45,7 +45,7 @@ public interface HttpFailureOperations { * * @throws ServiceException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse getNoModelError() throws ServiceException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperationsImpl.java index e704f8bcfbf15..9ee5a909d873c 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpFailureOperationsImpl.java @@ -67,7 +67,7 @@ interface HttpFailureService { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getEmptyError() throws ErrorException, IOException { Call call = service.getEmptyError(); @@ -112,7 +112,7 @@ private ServiceResponse getEmptyErrorDelegate(Response re * * @throws ServiceException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse getNoModelError() throws ServiceException, IOException { Call call = service.getNoModelError(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperations.java index a6a6fbcb5beff..f47159a00177d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperations.java @@ -44,7 +44,7 @@ public interface HttpSuccessOperations { * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ ServiceResponse get200() throws ErrorException, IOException; diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java index 792e759ec66f9..09ab15c84944e 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/http/HttpSuccessOperationsImpl.java @@ -182,7 +182,7 @@ private ServiceResponse head200Delegate(Response response) throws Er * * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization - * @return the Boolean object wrapped in {@link ServiceResponse} if successful. + * @return the boolean object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse get200() throws ErrorException, IOException { Call call = service.get200(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestService.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestService.java index 9cceedd84c296..f9141d25e0048 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestService.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestService.java @@ -290,13 +290,14 @@ public interface AutoRestResourceFlatteningTestService { * @param productId Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. * @param maxProductDisplayName Display name of product. * @param description Description of product. + * @param genericValue Generic URL value. * @param odatavalue URL value. * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the SimpleProduct object wrapped in {@link ServiceResponse} if successful. */ - ServiceResponse postFlattenedSimpleProduct(String productId, String maxProductDisplayName, String description, String odatavalue) throws ErrorException, IOException, IllegalArgumentException; + ServiceResponse postFlattenedSimpleProduct(String productId, String maxProductDisplayName, String description, String genericValue, String odatavalue) throws ErrorException, IOException, IllegalArgumentException; /** * Put Flattened Simple Product with client flattening true on the parameter. @@ -304,12 +305,13 @@ public interface AutoRestResourceFlatteningTestService { * @param productId Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. * @param maxProductDisplayName Display name of product. * @param description Description of product. + * @param genericValue Generic URL value. * @param odatavalue URL value. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall postFlattenedSimpleProductAsync(String productId, String maxProductDisplayName, String description, String odatavalue, final ServiceCallback serviceCallback) throws IllegalArgumentException; + ServiceCall postFlattenedSimpleProductAsync(String productId, String maxProductDisplayName, String description, String genericValue, String odatavalue, final ServiceCallback serviceCallback) throws IllegalArgumentException; /** * Put Simple Product with client flattening true on the model. diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java index a85d96f940b26..6a92545776db8 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/AutoRestResourceFlatteningTestServiceImpl.java @@ -670,15 +670,14 @@ public ServiceResponse postFlattenedSimpleProduct(String productI throw new IllegalArgumentException("Parameter maxProductDisplayName is required and cannot be null."); } final String description = null; + final String genericValue = null; final String odatavalue = null; - SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { - simpleBodyProduct = new SimpleProduct(); - simpleBodyProduct.setProductId(productId); - simpleBodyProduct.setDescription(description); - simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); - simpleBodyProduct.setOdatavalue(odatavalue); - } + SimpleProduct simpleBodyProduct = new SimpleProduct(); + simpleBodyProduct.setProductId(productId); + simpleBodyProduct = null; + simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct = null; + simpleBodyProduct = null; Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); return postFlattenedSimpleProductDelegate(call.execute()); } @@ -705,15 +704,14 @@ public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxP return null; } final String description = null; + final String genericValue = null; final String odatavalue = null; - SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { - simpleBodyProduct = new SimpleProduct(); - simpleBodyProduct.setProductId(productId); - simpleBodyProduct.setDescription(description); - simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); - simpleBodyProduct.setOdatavalue(odatavalue); - } + SimpleProduct simpleBodyProduct = new SimpleProduct(); + simpleBodyProduct.setProductId(productId); + simpleBodyProduct = null; + simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct = null; + simpleBodyProduct = null; Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @@ -735,13 +733,14 @@ public void onResponse(Call call, Response response) * @param productId Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. * @param maxProductDisplayName Display name of product. * @param description Description of product. + * @param genericValue Generic URL value. * @param odatavalue URL value. * @throws ErrorException exception thrown from REST call * @throws IOException exception thrown from serialization/deserialization * @throws IllegalArgumentException exception thrown from invalid parameters * @return the SimpleProduct object wrapped in {@link ServiceResponse} if successful. */ - public ServiceResponse postFlattenedSimpleProduct(String productId, String maxProductDisplayName, String description, String odatavalue) throws ErrorException, IOException, IllegalArgumentException { + public ServiceResponse postFlattenedSimpleProduct(String productId, String maxProductDisplayName, String description, String genericValue, String odatavalue) throws ErrorException, IOException, IllegalArgumentException { if (productId == null) { throw new IllegalArgumentException("Parameter productId is required and cannot be null."); } @@ -749,11 +748,12 @@ public ServiceResponse postFlattenedSimpleProduct(String productI throw new IllegalArgumentException("Parameter maxProductDisplayName is required and cannot be null."); } SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { + if (description != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct.setDescription(description); simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct.setGenericValue(genericValue); simpleBodyProduct.setOdatavalue(odatavalue); } Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); @@ -766,12 +766,13 @@ public ServiceResponse postFlattenedSimpleProduct(String productI * @param productId Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. * @param maxProductDisplayName Display name of product. * @param description Description of product. + * @param genericValue Generic URL value. * @param odatavalue URL value. * @param serviceCallback the async ServiceCallback to handle successful and failed responses. * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxProductDisplayName, String description, String odatavalue, final ServiceCallback serviceCallback) throws IllegalArgumentException { + public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxProductDisplayName, String description, String genericValue, String odatavalue, final ServiceCallback serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } @@ -784,11 +785,12 @@ public ServiceCall postFlattenedSimpleProductAsync(String productId, String maxP return null; } SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { + if (description != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct.setDescription(description); simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct.setGenericValue(genericValue); simpleBodyProduct.setOdatavalue(odatavalue); } Call call = service.postFlattenedSimpleProduct(simpleBodyProduct); @@ -831,13 +833,15 @@ public ServiceResponse putSimpleProductWithGrouping(FlattenParame String productId = flattenParameterGroup.getProductId(); String description = flattenParameterGroup.getDescription(); String maxProductDisplayName = flattenParameterGroup.getMaxProductDisplayName(); + String genericValue = flattenParameterGroup.getGenericValue(); String odatavalue = flattenParameterGroup.getOdatavalue(); SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { + if (description != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct.setDescription(description); simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct.setGenericValue(genericValue); simpleBodyProduct.setOdatavalue(odatavalue); } Call call = service.putSimpleProductWithGrouping(name, simpleBodyProduct); @@ -865,13 +869,15 @@ public ServiceCall putSimpleProductWithGroupingAsync(FlattenParameterGroup flatt String productId = flattenParameterGroup.getProductId(); String description = flattenParameterGroup.getDescription(); String maxProductDisplayName = flattenParameterGroup.getMaxProductDisplayName(); + String genericValue = flattenParameterGroup.getGenericValue(); String odatavalue = flattenParameterGroup.getOdatavalue(); SimpleProduct simpleBodyProduct = null; - if (description != null || odatavalue != null) { + if (description != null || genericValue != null || odatavalue != null) { simpleBodyProduct = new SimpleProduct(); simpleBodyProduct.setProductId(productId); simpleBodyProduct.setDescription(description); simpleBodyProduct.setMaxProductDisplayName(maxProductDisplayName); + simpleBodyProduct.setGenericValue(genericValue); simpleBodyProduct.setOdatavalue(odatavalue); } Call call = service.putSimpleProductWithGrouping(name, simpleBodyProduct); diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/FlattenParameterGroup.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/FlattenParameterGroup.java index a5c0ba649ee3a..342b622a71f03 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/FlattenParameterGroup.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/FlattenParameterGroup.java @@ -44,6 +44,12 @@ public class FlattenParameterGroup { @JsonProperty(value = "", required = true) private String maxProductDisplayName; + /** + * Generic URL value. + */ + @JsonProperty(value = "") + private String genericValue; + /** * URL value. */ @@ -122,6 +128,24 @@ public void setMaxProductDisplayName(String maxProductDisplayName) { this.maxProductDisplayName = maxProductDisplayName; } + /** + * Get the genericValue value. + * + * @return the genericValue value + */ + public String getGenericValue() { + return this.genericValue; + } + + /** + * Set the genericValue value. + * + * @param genericValue the genericValue value to set + */ + public void setGenericValue(String genericValue) { + this.genericValue = genericValue; + } + /** * Get the odatavalue value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/GenericUrl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/GenericUrl.java new file mode 100644 index 0000000000000..b5247b4e2b157 --- /dev/null +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/GenericUrl.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +package fixtures.modelflattening.models; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The Generic URL. + */ +public class GenericUrl { + /** + * Generic URL value. + */ + @JsonProperty(value = "generic_value") + private String genericValue; + + /** + * Get the genericValue value. + * + * @return the genericValue value + */ + public String getGenericValue() { + return this.genericValue; + } + + /** + * Set the genericValue value. + * + * @param genericValue the genericValue value to set + */ + public void setGenericValue(String genericValue) { + this.genericValue = genericValue; + } + +} diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/Resource.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/Resource.java index 2fec07db12f71..b838cc58de139 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/Resource.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/Resource.java @@ -10,8 +10,8 @@ package fixtures.modelflattening.models; -import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The Resource model. diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/SimpleProduct.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/SimpleProduct.java index 1ec1bcacbffa8..aad8d564f6c53 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/SimpleProduct.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/modelflattening/models/SimpleProduct.java @@ -30,6 +30,12 @@ public class SimpleProduct extends BaseProduct { @JsonProperty(value = "details.max_product_capacity", required = true) private String capacity; + /** + * Generic URL value. + */ + @JsonProperty(value = "details.max_product_image.generic_value") + private String genericValue; + /** * URL value. */ @@ -79,6 +85,24 @@ public void setCapacity(String capacity) { this.capacity = capacity; } + /** + * Get the genericValue value. + * + * @return the genericValue value + */ + public String getGenericValue() { + return this.genericValue; + } + + /** + * Set the genericValue value. + * + * @param genericValue the genericValue value to set + */ + public void setGenericValue(String genericValue) { + this.genericValue = genericValue; + } + /** * Get the odatavalue value. * diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java index 9beced52bb191..e0b711b87ac9d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/requiredoptional/ExplicitOperationsImpl.java @@ -1588,7 +1588,8 @@ public ServiceResponse postRequiredArrayHeader(List headerParamet throw new IllegalArgumentException("Parameter headerParameter is required and cannot be null."); } Validator.validate(headerParameter); - Call call = service.postRequiredArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postRequiredArrayHeader(headerParameterConverted); return postRequiredArrayHeaderDelegate(call.execute()); } @@ -1609,7 +1610,8 @@ public ServiceCall postRequiredArrayHeaderAsync(List headerParameter, fi return null; } Validator.validate(headerParameter, serviceCallback); - Call call = service.postRequiredArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postRequiredArrayHeader(headerParameterConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1638,8 +1640,8 @@ private ServiceResponse postRequiredArrayHeaderDelegate(Response postOptionalArrayHeader() throws ErrorException, IOException { - final List headerParameter = null; - Call call = service.postOptionalArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + final String headerParameterConverted = null; + Call call = service.postOptionalArrayHeader(headerParameterConverted); return postOptionalArrayHeaderDelegate(call.execute()); } @@ -1654,8 +1656,8 @@ public ServiceCall postOptionalArrayHeaderAsync(final ServiceCallback serv if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List headerParameter = null; - Call call = service.postOptionalArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + final String headerParameterConverted = null; + Call call = service.postOptionalArrayHeader(headerParameterConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1680,7 +1682,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse postOptionalArrayHeader(List headerParameter) throws ErrorException, IOException { Validator.validate(headerParameter); - Call call = service.postOptionalArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postOptionalArrayHeader(headerParameterConverted); return postOptionalArrayHeaderDelegate(call.execute()); } @@ -1697,7 +1700,8 @@ public ServiceCall postOptionalArrayHeaderAsync(List headerParameter, fi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(headerParameter, serviceCallback); - Call call = service.postOptionalArrayHeader(this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV)); + String headerParameterConverted = this.client.getMapperAdapter().serializeList(headerParameter, CollectionFormat.CSV); + Call call = service.postOptionalArrayHeader(headerParameterConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java index cbf2ea2bd0265..f7676a65a59a3 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java @@ -16,6 +16,7 @@ import fixtures.url.models.ErrorException; import fixtures.url.models.UriColor; import java.io.IOException; +import java.util.List; import org.joda.time.DateTime; import org.joda.time.LocalDate; @@ -459,4 +460,46 @@ public interface PathsOperations { */ ServiceCall dateTimeNullAsync(DateTime dateTimePath, final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url). + * + * @param base64UrlPath base64url encoded value + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse base64Url(String base64UrlPath) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url). + * + * @param base64UrlPath base64url encoded value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall base64UrlAsync(String base64UrlPath, final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format. + * + * @param arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + ServiceResponse arrayCsvInPath(List arrayPath) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format. + * + * @param arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall arrayCsvInPathAsync(List arrayPath, final ServiceCallback serviceCallback) throws IllegalArgumentException; + } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java index 0786c24f6b576..b32c2fcbd2471 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperationsImpl.java @@ -11,14 +11,17 @@ package fixtures.url; import com.google.common.reflect.TypeToken; +import com.microsoft.rest.serializer.CollectionFormat; import com.microsoft.rest.ServiceCall; import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceResponse; import com.microsoft.rest.ServiceResponseBuilder; import com.microsoft.rest.ServiceResponseCallback; +import com.microsoft.rest.Validator; import fixtures.url.models.ErrorException; import fixtures.url.models.UriColor; import java.io.IOException; +import java.util.List; import okhttp3.ResponseBody; import org.apache.commons.codec.binary.Base64; import org.joda.time.DateTime; @@ -114,11 +117,11 @@ interface PathsService { @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/enum/green%20color/{enumPath}") - Call enumValid(@Path("enumPath") String enumPath); + Call enumValid(@Path("enumPath") UriColor enumPath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/string/null/{enumPath}") - Call enumNull(@Path("enumPath") String enumPath); + Call enumNull(@Path("enumPath") UriColor enumPath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/byte/multibyte/{bytePath}") @@ -134,19 +137,27 @@ interface PathsService { @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/date/2012-01-01/{datePath}") - Call dateValid(@Path("datePath") String datePath); + Call dateValid(@Path("datePath") LocalDate datePath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/date/null/{datePath}") - Call dateNull(@Path("datePath") String datePath); + Call dateNull(@Path("datePath") LocalDate datePath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/datetime/2012-01-01T01%3A01%3A01Z/{dateTimePath}") - Call dateTimeValid(@Path("dateTimePath") String dateTimePath); + Call dateTimeValid(@Path("dateTimePath") DateTime dateTimePath); @Headers("Content-Type: application/json; charset=utf-8") @GET("paths/datetime/null/{dateTimePath}") - Call dateTimeNull(@Path("dateTimePath") String dateTimePath); + Call dateTimeNull(@Path("dateTimePath") DateTime dateTimePath); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("paths/string/bG9yZW0/{base64UrlPath}") + Call base64Url(@Path("base64UrlPath") String base64UrlPath); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath:commaSeparated}") + Call arrayCsvInPath(@Path("arrayPath") String arrayPath); } @@ -829,7 +840,7 @@ public ServiceResponse enumValid(UriColor enumPath) throws ErrorException, if (enumPath == null) { throw new IllegalArgumentException("Parameter enumPath is required and cannot be null."); } - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumPath)); + Call call = service.enumValid(enumPath); return enumValidDelegate(call.execute()); } @@ -849,7 +860,7 @@ public ServiceCall enumValidAsync(UriColor enumPath, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter enumPath is required and cannot be null.")); return null; } - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumPath)); + Call call = service.enumValid(enumPath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -884,7 +895,7 @@ public ServiceResponse enumNull(UriColor enumPath) throws ErrorException, if (enumPath == null) { throw new IllegalArgumentException("Parameter enumPath is required and cannot be null."); } - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumPath)); + Call call = service.enumNull(enumPath); return enumNullDelegate(call.execute()); } @@ -904,7 +915,7 @@ public ServiceCall enumNullAsync(UriColor enumPath, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter enumPath is required and cannot be null.")); return null; } - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumPath)); + Call call = service.enumNull(enumPath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -939,7 +950,8 @@ public ServiceResponse byteMultiByte(byte[] bytePath) throws ErrorExceptio if (bytePath == null) { throw new IllegalArgumentException("Parameter bytePath is required and cannot be null."); } - Call call = service.byteMultiByte(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteMultiByte(bytePathConverted); return byteMultiByteDelegate(call.execute()); } @@ -959,7 +971,8 @@ public ServiceCall byteMultiByteAsync(byte[] bytePath, final ServiceCallback call = service.byteMultiByte(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteMultiByte(bytePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -990,7 +1003,8 @@ private ServiceResponse byteMultiByteDelegate(Response respo */ public ServiceResponse byteEmpty() throws ErrorException, IOException { final byte[] bytePath = "".getBytes(); - Call call = service.byteEmpty(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteEmpty(bytePathConverted); return byteEmptyDelegate(call.execute()); } @@ -1006,7 +1020,8 @@ public ServiceCall byteEmptyAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final byte[] bytePath = "".getBytes(); - Call call = service.byteEmpty(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteEmpty(bytePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1041,7 +1056,8 @@ public ServiceResponse byteNull(byte[] bytePath) throws ErrorException, IO if (bytePath == null) { throw new IllegalArgumentException("Parameter bytePath is required and cannot be null."); } - Call call = service.byteNull(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteNull(bytePathConverted); return byteNullDelegate(call.execute()); } @@ -1061,7 +1077,8 @@ public ServiceCall byteNullAsync(byte[] bytePath, final ServiceCallback se serviceCallback.failure(new IllegalArgumentException("Parameter bytePath is required and cannot be null.")); return null; } - Call call = service.byteNull(Base64.encodeBase64String(bytePath)); + String bytePathConverted = Base64.encodeBase64String(bytePath); + Call call = service.byteNull(bytePathConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1092,7 +1109,7 @@ private ServiceResponse byteNullDelegate(Response response) */ public ServiceResponse dateValid() throws ErrorException, IOException { final LocalDate datePath = LocalDate.parse("2012-01-01"); - Call call = service.dateValid(this.client.getMapperAdapter().serializeRaw(datePath)); + Call call = service.dateValid(datePath); return dateValidDelegate(call.execute()); } @@ -1108,7 +1125,7 @@ public ServiceCall dateValidAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final LocalDate datePath = LocalDate.parse("2012-01-01"); - Call call = service.dateValid(this.client.getMapperAdapter().serializeRaw(datePath)); + Call call = service.dateValid(datePath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1143,7 +1160,7 @@ public ServiceResponse dateNull(LocalDate datePath) throws ErrorException, if (datePath == null) { throw new IllegalArgumentException("Parameter datePath is required and cannot be null."); } - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(datePath)); + Call call = service.dateNull(datePath); return dateNullDelegate(call.execute()); } @@ -1163,7 +1180,7 @@ public ServiceCall dateNullAsync(LocalDate datePath, final ServiceCallback serviceCallback.failure(new IllegalArgumentException("Parameter datePath is required and cannot be null.")); return null; } - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(datePath)); + Call call = service.dateNull(datePath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1194,7 +1211,7 @@ private ServiceResponse dateNullDelegate(Response response) */ public ServiceResponse dateTimeValid() throws ErrorException, IOException { final DateTime dateTimePath = DateTime.parse("2012-01-01T01:01:01Z"); - Call call = service.dateTimeValid(this.client.getMapperAdapter().serializeRaw(dateTimePath)); + Call call = service.dateTimeValid(dateTimePath); return dateTimeValidDelegate(call.execute()); } @@ -1210,7 +1227,7 @@ public ServiceCall dateTimeValidAsync(final ServiceCallback serviceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final DateTime dateTimePath = DateTime.parse("2012-01-01T01:01:01Z"); - Call call = service.dateTimeValid(this.client.getMapperAdapter().serializeRaw(dateTimePath)); + Call call = service.dateTimeValid(dateTimePath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1245,7 +1262,7 @@ public ServiceResponse dateTimeNull(DateTime dateTimePath) throws ErrorExc if (dateTimePath == null) { throw new IllegalArgumentException("Parameter dateTimePath is required and cannot be null."); } - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimePath)); + Call call = service.dateTimeNull(dateTimePath); return dateTimeNullDelegate(call.execute()); } @@ -1265,7 +1282,7 @@ public ServiceCall dateTimeNullAsync(DateTime dateTimePath, final ServiceCallbac serviceCallback.failure(new IllegalArgumentException("Parameter dateTimePath is required and cannot be null.")); return null; } - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimePath)); + Call call = service.dateTimeNull(dateTimePath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1287,4 +1304,118 @@ private ServiceResponse dateTimeNullDelegate(Response respon .build(response); } + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url). + * + * @param base64UrlPath base64url encoded value + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse base64Url(String base64UrlPath) throws ErrorException, IOException, IllegalArgumentException { + if (base64UrlPath == null) { + throw new IllegalArgumentException("Parameter base64UrlPath is required and cannot be null."); + } + Call call = service.base64Url(base64UrlPath); + return base64UrlDelegate(call.execute()); + } + + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url). + * + * @param base64UrlPath base64url encoded value + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall base64UrlAsync(String base64UrlPath, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (base64UrlPath == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter base64UrlPath is required and cannot be null.")); + return null; + } + Call call = service.base64Url(base64UrlPath); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(base64UrlDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse base64UrlDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format. + * + * @param arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws IllegalArgumentException exception thrown from invalid parameters + * @return the {@link ServiceResponse} object if successful. + */ + public ServiceResponse arrayCsvInPath(List arrayPath) throws ErrorException, IOException, IllegalArgumentException { + if (arrayPath == null) { + throw new IllegalArgumentException("Parameter arrayPath is required and cannot be null."); + } + Validator.validate(arrayPath); + String arrayPathConverted = this.client.getMapperAdapter().serializeList(arrayPath, CollectionFormat.CSV); + Call call = service.arrayCsvInPath(arrayPathConverted); + return arrayCsvInPathDelegate(call.execute()); + } + + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format. + * + * @param arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link Call} object + */ + public ServiceCall arrayCsvInPathAsync(List arrayPath, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (arrayPath == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter arrayPath is required and cannot be null.")); + return null; + } + Validator.validate(arrayPath, serviceCallback); + String arrayPathConverted = this.client.getMapperAdapter().serializeList(arrayPath, CollectionFormat.CSV); + Call call = service.arrayCsvInPath(arrayPathConverted); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(arrayCsvInPathDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse arrayCsvInPathDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java index 864bbb1badf44..5cb35d0f1043d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/QueriesOperationsImpl.java @@ -137,11 +137,11 @@ interface QueriesService { @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/enum/green%20color") - Call enumValid(@Query("enumQuery") String enumQuery); + Call enumValid(@Query("enumQuery") UriColor enumQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/enum/null") - Call enumNull(@Query("enumQuery") String enumQuery); + Call enumNull(@Query("enumQuery") UriColor enumQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/byte/multibyte") @@ -157,19 +157,19 @@ interface QueriesService { @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/date/2012-01-01") - Call dateValid(@Query("dateQuery") String dateQuery); + Call dateValid(@Query("dateQuery") LocalDate dateQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/date/null") - Call dateNull(@Query("dateQuery") String dateQuery); + Call dateNull(@Query("dateQuery") LocalDate dateQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/datetime/2012-01-01T01%3A01%3A01Z") - Call dateTimeValid(@Query("dateTimeQuery") String dateTimeQuery); + Call dateTimeValid(@Query("dateTimeQuery") DateTime dateTimeQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/datetime/null") - Call dateTimeNull(@Query("dateTimeQuery") String dateTimeQuery); + Call dateTimeNull(@Query("dateTimeQuery") DateTime dateTimeQuery); @Headers("Content-Type: application/json; charset=utf-8") @GET("queries/array/csv/string/valid") @@ -1339,7 +1339,7 @@ private ServiceResponse stringNullDelegate(Response response */ public ServiceResponse enumValid() throws ErrorException, IOException { final UriColor enumQuery = null; - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumQuery)); + Call call = service.enumValid(enumQuery); return enumValidDelegate(call.execute()); } @@ -1355,7 +1355,7 @@ public ServiceCall enumValidAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final UriColor enumQuery = null; - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumQuery)); + Call call = service.enumValid(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1379,7 +1379,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumValid(UriColor enumQuery) throws ErrorException, IOException { - Call call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumQuery)); + Call call = service.enumValid(enumQuery); return enumValidDelegate(call.execute()); } @@ -1395,7 +1395,7 @@ public ServiceCall enumValidAsync(UriColor enumQuery, final ServiceCallback call = service.enumValid(this.client.getMapperAdapter().serializeRaw(enumQuery)); + Call call = service.enumValid(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1426,7 +1426,7 @@ private ServiceResponse enumValidDelegate(Response response) */ public ServiceResponse enumNull() throws ErrorException, IOException { final UriColor enumQuery = null; - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumQuery)); + Call call = service.enumNull(enumQuery); return enumNullDelegate(call.execute()); } @@ -1442,7 +1442,7 @@ public ServiceCall enumNullAsync(final ServiceCallback serviceCallback) th throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final UriColor enumQuery = null; - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumQuery)); + Call call = service.enumNull(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1466,7 +1466,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse enumNull(UriColor enumQuery) throws ErrorException, IOException { - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumQuery)); + Call call = service.enumNull(enumQuery); return enumNullDelegate(call.execute()); } @@ -1482,7 +1482,7 @@ public ServiceCall enumNullAsync(UriColor enumQuery, final ServiceCallback if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.enumNull(this.client.getMapperAdapter().serializeRaw(enumQuery)); + Call call = service.enumNull(enumQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1512,8 +1512,8 @@ private ServiceResponse enumNullDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteMultiByte() throws ErrorException, IOException { - final byte[] byteQuery = null; - Call call = service.byteMultiByte(Base64.encodeBase64String(byteQuery)); + final String byteQueryConverted = null; + Call call = service.byteMultiByte(byteQueryConverted); return byteMultiByteDelegate(call.execute()); } @@ -1528,8 +1528,8 @@ public ServiceCall byteMultiByteAsync(final ServiceCallback serviceCallbac if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final byte[] byteQuery = null; - Call call = service.byteMultiByte(Base64.encodeBase64String(byteQuery)); + final String byteQueryConverted = null; + Call call = service.byteMultiByte(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1553,7 +1553,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteMultiByte(byte[] byteQuery) throws ErrorException, IOException { - Call call = service.byteMultiByte(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteMultiByte(byteQueryConverted); return byteMultiByteDelegate(call.execute()); } @@ -1569,7 +1570,8 @@ public ServiceCall byteMultiByteAsync(byte[] byteQuery, final ServiceCallback call = service.byteMultiByte(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteMultiByte(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1600,7 +1602,8 @@ private ServiceResponse byteMultiByteDelegate(Response respo */ public ServiceResponse byteEmpty() throws ErrorException, IOException { final byte[] byteQuery = "".getBytes(); - Call call = service.byteEmpty(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteEmpty(byteQueryConverted); return byteEmptyDelegate(call.execute()); } @@ -1616,7 +1619,8 @@ public ServiceCall byteEmptyAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final byte[] byteQuery = "".getBytes(); - Call call = service.byteEmpty(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteEmpty(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1646,8 +1650,8 @@ private ServiceResponse byteEmptyDelegate(Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteNull() throws ErrorException, IOException { - final byte[] byteQuery = null; - Call call = service.byteNull(Base64.encodeBase64String(byteQuery)); + final String byteQueryConverted = null; + Call call = service.byteNull(byteQueryConverted); return byteNullDelegate(call.execute()); } @@ -1662,8 +1666,8 @@ public ServiceCall byteNullAsync(final ServiceCallback serviceCallback) th if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final byte[] byteQuery = null; - Call call = service.byteNull(Base64.encodeBase64String(byteQuery)); + final String byteQueryConverted = null; + Call call = service.byteNull(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1687,7 +1691,8 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse byteNull(byte[] byteQuery) throws ErrorException, IOException { - Call call = service.byteNull(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteNull(byteQueryConverted); return byteNullDelegate(call.execute()); } @@ -1703,7 +1708,8 @@ public ServiceCall byteNullAsync(byte[] byteQuery, final ServiceCallback s if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.byteNull(Base64.encodeBase64String(byteQuery)); + String byteQueryConverted = Base64.encodeBase64String(byteQuery); + Call call = service.byteNull(byteQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1734,7 +1740,7 @@ private ServiceResponse byteNullDelegate(Response response) */ public ServiceResponse dateValid() throws ErrorException, IOException { final LocalDate dateQuery = LocalDate.parse("2012-01-01"); - Call call = service.dateValid(this.client.getMapperAdapter().serializeRaw(dateQuery)); + Call call = service.dateValid(dateQuery); return dateValidDelegate(call.execute()); } @@ -1750,7 +1756,7 @@ public ServiceCall dateValidAsync(final ServiceCallback serviceCallback) t throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final LocalDate dateQuery = LocalDate.parse("2012-01-01"); - Call call = service.dateValid(this.client.getMapperAdapter().serializeRaw(dateQuery)); + Call call = service.dateValid(dateQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1781,7 +1787,7 @@ private ServiceResponse dateValidDelegate(Response response) */ public ServiceResponse dateNull() throws ErrorException, IOException { final LocalDate dateQuery = null; - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(dateQuery)); + Call call = service.dateNull(dateQuery); return dateNullDelegate(call.execute()); } @@ -1797,7 +1803,7 @@ public ServiceCall dateNullAsync(final ServiceCallback serviceCallback) th throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final LocalDate dateQuery = null; - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(dateQuery)); + Call call = service.dateNull(dateQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1821,7 +1827,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateNull(LocalDate dateQuery) throws ErrorException, IOException { - Call call = service.dateNull(this.client.getMapperAdapter().serializeRaw(dateQuery)); + Call call = service.dateNull(dateQuery); return dateNullDelegate(call.execute()); } @@ -1837,7 +1843,7 @@ public ServiceCall dateNullAsync(LocalDate dateQuery, final ServiceCallback call = service.dateNull(this.client.getMapperAdapter().serializeRaw(dateQuery)); + Call call = service.dateNull(dateQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1868,7 +1874,7 @@ private ServiceResponse dateNullDelegate(Response response) */ public ServiceResponse dateTimeValid() throws ErrorException, IOException { final DateTime dateTimeQuery = DateTime.parse("2012-01-01T01:01:01Z"); - Call call = service.dateTimeValid(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + Call call = service.dateTimeValid(dateTimeQuery); return dateTimeValidDelegate(call.execute()); } @@ -1884,7 +1890,7 @@ public ServiceCall dateTimeValidAsync(final ServiceCallback serviceCallbac throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final DateTime dateTimeQuery = DateTime.parse("2012-01-01T01:01:01Z"); - Call call = service.dateTimeValid(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + Call call = service.dateTimeValid(dateTimeQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1915,7 +1921,7 @@ private ServiceResponse dateTimeValidDelegate(Response respo */ public ServiceResponse dateTimeNull() throws ErrorException, IOException { final DateTime dateTimeQuery = null; - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + Call call = service.dateTimeNull(dateTimeQuery); return dateTimeNullDelegate(call.execute()); } @@ -1931,7 +1937,7 @@ public ServiceCall dateTimeNullAsync(final ServiceCallback serviceCallback throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final DateTime dateTimeQuery = null; - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + Call call = service.dateTimeNull(dateTimeQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1955,7 +1961,7 @@ public void onResponse(Call call, Response response) * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse dateTimeNull(DateTime dateTimeQuery) throws ErrorException, IOException { - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + Call call = service.dateTimeNull(dateTimeQuery); return dateTimeNullDelegate(call.execute()); } @@ -1971,7 +1977,7 @@ public ServiceCall dateTimeNullAsync(DateTime dateTimeQuery, final ServiceCallba if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.dateTimeNull(this.client.getMapperAdapter().serializeRaw(dateTimeQuery)); + Call call = service.dateTimeNull(dateTimeQuery); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2001,8 +2007,8 @@ private ServiceResponse dateTimeNullDelegate(Response respon * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringCsvValid() throws ErrorException, IOException { - final List arrayQuery = null; - Call call = service.arrayStringCsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvValid(arrayQueryConverted); return arrayStringCsvValidDelegate(call.execute()); } @@ -2017,8 +2023,8 @@ public ServiceCall arrayStringCsvValidAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - Call call = service.arrayStringCsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2043,7 +2049,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringCsvValid(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringCsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvValid(arrayQueryConverted); return arrayStringCsvValidDelegate(call.execute()); } @@ -2060,7 +2067,8 @@ public ServiceCall arrayStringCsvValidAsync(List arrayQuery, final Servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringCsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2090,8 +2098,8 @@ private ServiceResponse arrayStringCsvValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringCsvNull() throws ErrorException, IOException { - final List arrayQuery = null; - Call call = service.arrayStringCsvNull(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvNull(arrayQueryConverted); return arrayStringCsvNullDelegate(call.execute()); } @@ -2106,8 +2114,8 @@ public ServiceCall arrayStringCsvNullAsync(final ServiceCallback serviceCa if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - Call call = service.arrayStringCsvNull(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvNull(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2132,7 +2140,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringCsvNull(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringCsvNull(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvNull(arrayQueryConverted); return arrayStringCsvNullDelegate(call.execute()); } @@ -2149,7 +2158,8 @@ public ServiceCall arrayStringCsvNullAsync(List arrayQuery, final Servic throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringCsvNull(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvNull(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2179,8 +2189,8 @@ private ServiceResponse arrayStringCsvNullDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringCsvEmpty() throws ErrorException, IOException { - final List arrayQuery = null; - Call call = service.arrayStringCsvEmpty(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); return arrayStringCsvEmptyDelegate(call.execute()); } @@ -2195,8 +2205,8 @@ public ServiceCall arrayStringCsvEmptyAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - Call call = service.arrayStringCsvEmpty(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2221,7 +2231,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringCsvEmpty(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringCsvEmpty(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); return arrayStringCsvEmptyDelegate(call.execute()); } @@ -2238,7 +2249,8 @@ public ServiceCall arrayStringCsvEmptyAsync(List arrayQuery, final Servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringCsvEmpty(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.CSV); + Call call = service.arrayStringCsvEmpty(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2268,8 +2280,8 @@ private ServiceResponse arrayStringCsvEmptyDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringSsvValid() throws ErrorException, IOException { - final List arrayQuery = null; - Call call = service.arrayStringSsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringSsvValid(arrayQueryConverted); return arrayStringSsvValidDelegate(call.execute()); } @@ -2284,8 +2296,8 @@ public ServiceCall arrayStringSsvValidAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - Call call = service.arrayStringSsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringSsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2310,7 +2322,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringSsvValid(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringSsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV); + Call call = service.arrayStringSsvValid(arrayQueryConverted); return arrayStringSsvValidDelegate(call.execute()); } @@ -2327,7 +2340,8 @@ public ServiceCall arrayStringSsvValidAsync(List arrayQuery, final Servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringSsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.SSV); + Call call = service.arrayStringSsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2357,8 +2371,8 @@ private ServiceResponse arrayStringSsvValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringTsvValid() throws ErrorException, IOException { - final List arrayQuery = null; - Call call = service.arrayStringTsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringTsvValid(arrayQueryConverted); return arrayStringTsvValidDelegate(call.execute()); } @@ -2373,8 +2387,8 @@ public ServiceCall arrayStringTsvValidAsync(final ServiceCallback serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - Call call = service.arrayStringTsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV)); + final String arrayQueryConverted = null; + Call call = service.arrayStringTsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2399,7 +2413,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringTsvValid(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringTsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV); + Call call = service.arrayStringTsvValid(arrayQueryConverted); return arrayStringTsvValidDelegate(call.execute()); } @@ -2416,7 +2431,8 @@ public ServiceCall arrayStringTsvValidAsync(List arrayQuery, final Servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringTsvValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.TSV); + Call call = service.arrayStringTsvValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2446,8 +2462,8 @@ private ServiceResponse arrayStringTsvValidDelegate(Response * @return the {@link ServiceResponse} object if successful. */ public ServiceResponse arrayStringPipesValid() throws ErrorException, IOException { - final List arrayQuery = null; - Call call = service.arrayStringPipesValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES)); + final String arrayQueryConverted = null; + Call call = service.arrayStringPipesValid(arrayQueryConverted); return arrayStringPipesValidDelegate(call.execute()); } @@ -2462,8 +2478,8 @@ public ServiceCall arrayStringPipesValidAsync(final ServiceCallback servic if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List arrayQuery = null; - Call call = service.arrayStringPipesValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES)); + final String arrayQueryConverted = null; + Call call = service.arrayStringPipesValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -2488,7 +2504,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse arrayStringPipesValid(List arrayQuery) throws ErrorException, IOException { Validator.validate(arrayQuery); - Call call = service.arrayStringPipesValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES); + Call call = service.arrayStringPipesValid(arrayQueryConverted); return arrayStringPipesValidDelegate(call.execute()); } @@ -2505,7 +2522,8 @@ public ServiceCall arrayStringPipesValidAsync(List arrayQuery, final Ser throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(arrayQuery, serviceCallback); - Call call = service.arrayStringPipesValid(this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES)); + String arrayQueryConverted = this.client.getMapperAdapter().serializeList(arrayQuery, CollectionFormat.PIPES); + Call call = service.arrayStringPipesValid(arrayQueryConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/models/UriColor.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/models/UriColor.java index 52d1b406a9d22..3eee3e193106a 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/models/UriColor.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/models/UriColor.java @@ -59,4 +59,9 @@ public static UriColor fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/models/EnumConst.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/models/EnumConst.java index a988f2ca28906..ced5c30d1fca2 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/models/EnumConst.java +++ b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/validation/models/EnumConst.java @@ -53,4 +53,9 @@ public static EnumConst fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyarray/ArrayTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyarray/ArrayTests.java index fec4046bf5035..03b7e211ba6b3 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyarray/ArrayTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyarray/ArrayTests.java @@ -3,9 +3,7 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.exc.InvalidFormatException; -import com.microsoft.rest.DateTimeRfc1123; -import fixtures.bodyarray.models.ErrorException; -import fixtures.bodyarray.models.Product; + import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; @@ -21,6 +19,9 @@ import java.util.Map; import java.util.UUID; +import fixtures.bodyarray.models.ErrorException; +import fixtures.bodyarray.models.Product; + public class ArrayTests { private static AutoRestSwaggerBATArrayService client; @@ -355,11 +356,11 @@ public void getDateTimeInvalidString() throws Exception { @Test public void getDateTimeRfc1123Valid() throws Exception { - List result = client.getArrayOperations().getDateTimeRfc1123Valid().getBody(); - Object[] expected = new DateTimeRfc1123[] { - new DateTimeRfc1123(new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC)), - new DateTimeRfc1123(new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC)), - new DateTimeRfc1123(new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC)) + List result = client.getArrayOperations().getDateTimeRfc1123Valid().getBody(); + Object[] expected = new DateTime[] { + new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC), + new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC), + new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC) }; Assert.assertArrayEquals(expected, result.toArray()); } @@ -367,9 +368,9 @@ public void getDateTimeRfc1123Valid() throws Exception { @Test public void putDateTimeRfc1123Valid() throws Exception { client.getArrayOperations().putDateTimeRfc1123Valid(Arrays.asList( - new DateTimeRfc1123(new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC)), - new DateTimeRfc1123(new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC)), - new DateTimeRfc1123(new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC)) + new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC), + new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC), + new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC) )); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodydictionary/DictionaryTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodydictionary/DictionaryTests.java index 1847a7a209a8d..688bd71cfa805 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodydictionary/DictionaryTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodydictionary/DictionaryTests.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.exc.InvalidFormatException; -import com.microsoft.rest.DateTimeRfc1123; import fixtures.bodydictionary.models.Widget; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; @@ -371,20 +370,20 @@ public void getDateTimeInvalidString() throws Exception { @Test public void getDateTimeRfc1123Valid() throws Exception { - Map result = client.getDictionaryOperations().getDateTimeRfc1123Valid().getBody(); - Map expected = new HashMap(); - expected.put("0", new DateTimeRfc1123(new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC))); - expected.put("1", new DateTimeRfc1123(new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC))); - expected.put("2", new DateTimeRfc1123(new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC))); + Map result = client.getDictionaryOperations().getDateTimeRfc1123Valid().getBody(); + Map expected = new HashMap(); + expected.put("0", new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC)); + expected.put("1", new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC)); + expected.put("2", new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC)); Assert.assertEquals(expected, result); } @Test public void putDateTimeRfc1123Valid() throws Exception { - Map testdata = new HashMap(); - testdata.put("0", new DateTimeRfc1123(new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC))); - testdata.put("1", new DateTimeRfc1123(new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC))); - testdata.put("2", new DateTimeRfc1123(new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC))); + Map testdata = new HashMap(); + testdata.put("0", new DateTime(2000, 12, 1, 0, 0, 1, DateTimeZone.UTC)); + testdata.put("1", new DateTime(1980, 1, 2, 0, 11, 35, DateTimeZone.UTC)); + testdata.put("2", new DateTime(1492, 10, 12, 10, 15, 1, DateTimeZone.UTC)); client.getDictionaryOperations().putDateTimeRfc1123Valid(testdata); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyfile/FilesTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyfile/FilesTests.java index b25cfb18b3f21..9843874e5b23d 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyfile/FilesTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/bodyfile/FilesTests.java @@ -1,19 +1,23 @@ package fixtures.bodyfile; -import org.junit.Assert; import org.apache.commons.io.IOUtils; +import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; -import org.junit.Ignore; import java.io.InputStream; +import java.util.concurrent.TimeUnit; + +import okhttp3.OkHttpClient; +import retrofit2.Retrofit; public class FilesTests { private static AutoRestSwaggerBATFileService client; @BeforeClass public static void setup() { - client = new AutoRestSwaggerBATFileServiceImpl("http://localhost.:3000"); + OkHttpClient.Builder builder = new OkHttpClient.Builder().readTimeout(1, TimeUnit.MINUTES); + client = new AutoRestSwaggerBATFileServiceImpl("http://localhost.:3000", builder, new Retrofit.Builder()); } @Test @@ -27,11 +31,10 @@ public void getFile() throws Exception { } } - @Ignore("This fails -- needs to be fixed") + @Test public void getLargeFile() throws Exception { - ClassLoader classLoader = getClass().getClassLoader(); try (InputStream result = client.getFilesOperations().getFileLarge().getBody()) { - long streamSize = 3000 * 1024 * 1024; + long streamSize = 3000L * 1024L * 1024L; long skipped = result.skip(streamSize); Assert.assertEquals(streamSize, skipped); } diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/modelflattening/ModelFlatteningTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/modelflattening/ModelFlatteningTests.java index 8e72c306543b6..5472617de5b5a 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/modelflattening/ModelFlatteningTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/modelflattening/ModelFlatteningTests.java @@ -204,6 +204,7 @@ public void putSimpleProduct() throws Exception { simpleProduct.setMaxProductDisplayName("max name"); simpleProduct.setCapacity("Large"); simpleProduct.setOdatavalue("http://foo"); + simpleProduct.setGenericValue("https://generic"); SimpleProduct product = client.putSimpleProduct(simpleProduct).getBody(); assertSimpleProductEquals(simpleProduct, product); @@ -217,7 +218,7 @@ public void postFlattenedSimpleProduct() throws Exception { simpleProduct.setMaxProductDisplayName("max name"); simpleProduct.setCapacity("Large"); simpleProduct.setOdatavalue("http://foo"); - client.postFlattenedSimpleProduct("123", "max name", "product description", "http://foo"); + client.postFlattenedSimpleProduct("123", "max name", "product description", null, "http://foo"); } @Test diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/report/CoverageReporter.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/report/CoverageReporter.java index 4c6d1f4099264..f394131cc8b52 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/report/CoverageReporter.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/report/CoverageReporter.java @@ -29,8 +29,6 @@ public static void main(String[] args) throws Exception { report.put("HttpRedirect301Put", 1); report.put("HttpRedirect302Patch", 1); - report.put("FileStreamVeryLarge", 1); - int total = report.size(); int hit = 0; List missing = new ArrayList<>(); diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/PathsTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/PathsTests.java index 710e949f7093b..4aa614e9bc02b 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/PathsTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/PathsTests.java @@ -143,4 +143,15 @@ public void dateTimeNull() throws Exception { Assert.assertTrue(ex.getMessage().contains("Parameter dateTimePath is required")); } } + /* + @Test + public void arrayCsvInPath() throws Exception { + List arrayPath = new ArrayList<>(); + arrayPath.add("ArrayPath1"); + arrayPath.add("begin!*'();:@ &=+$,/?#[]end"); + arrayPath.add(null); + arrayPath.add(""); + client.getPathsOperations().arrayCsvInPath(arrayPath); + } + */ } diff --git a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/QueriesTests.java b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/QueriesTests.java index 3f994b736f0cb..a8d1b48161701 100644 --- a/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/QueriesTests.java +++ b/AutoRest/Generators/Java/Java.Tests/src/test/java/fixtures/url/QueriesTests.java @@ -9,6 +9,7 @@ import fixtures.url.models.ErrorException; import fixtures.url.models.UriColor; +import okhttp3.logging.HttpLoggingInterceptor; public class QueriesTests { private static AutoRestUrlTestService client; @@ -16,6 +17,7 @@ public class QueriesTests { @BeforeClass public static void setup() { client = new AutoRestUrlTestServiceImpl("http://localhost.:3000"); + client.setLogLevel(HttpLoggingInterceptor.Level.HEADERS); } @Test diff --git a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj index 53febfee98847..e1287ab35efdf 100644 --- a/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj +++ b/AutoRest/Generators/Java/Java/AutoRest.Generator.Java.csproj @@ -32,6 +32,15 @@ Resources.resx + + + + + + + + + diff --git a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs index e7ef1baa88fda..dccdc10f9cee1 100644 --- a/AutoRest/Generators/Java/Java/ClientModelExtensions.cs +++ b/AutoRest/Generators/Java/Java/ClientModelExtensions.cs @@ -15,51 +15,6 @@ public static class ClientModelExtensions { public const string ExternalExtension = "x-ms-external"; - public static bool NeedsSpecialSerialization(this IType type) - { - var known = type as PrimaryType; - return (known != null && (known.Name == "LocalDate" || known.Name == "DateTime" || known.Type == KnownPrimaryType.ByteArray)) || - type is EnumType || type is CompositeType || type is SequenceType || type is DictionaryType; - } - - /// - /// Simple conversion of the type to string - /// - /// The parameter to convert - /// a reference to an instance of the type - /// a reference to the service client - /// - public static string ToString(this Parameter parameter, string reference, string clientReference) - { - if (parameter == null) - { - return null; - } - var type = parameter.Type; - var known = type as PrimaryType; - var sequence = type as SequenceType; - if (known != null && known.Name != "LocalDate" && known.Name != "DateTime") - { - if (known.Type == KnownPrimaryType.ByteArray) - { - return "Base64.encodeBase64String(" + reference + ")"; - } - else - { - return reference; - } - } - else if (sequence != null) - { - return clientReference + ".getMapperAdapter().serializeList(" + reference + - ", CollectionFormat." + parameter.CollectionFormat.ToString().ToUpper(CultureInfo.InvariantCulture) + ")"; - } - else - { - return clientReference + ".getMapperAdapter().serializeRaw(" + reference + ")"; - } - } - public static string Period(this string documentation) { if (string.IsNullOrEmpty(documentation)) @@ -124,58 +79,18 @@ public static void AddRange(this HashSet hashSet, IEnumerable range) } } - public static IType UserHandledType(this IType type) - { - PrimaryType primaryType = type as PrimaryType; - if (primaryType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - { - return new PrimaryType(KnownPrimaryType.DateTime); - } - else - { - return type; - } - } - - public static List ImportFrom(this IType type, string ns, JavaCodeNamer namer) - { - if (namer == null) - { - return null; - } - return namer.ImportType(type, ns); - } - - public static List ImportFrom(this Parameter parameter) + /// + /// A null friendly wrapper around type imports. + /// + /// an instance of IJavaType + /// a list of imports to append + public static IEnumerable ImportSafe(this IType type) { - List imports = new List(); - if (parameter == null) - { - return imports; - } - var type = parameter.Type; - - SequenceType sequenceType = type as SequenceType; - if (type.IsPrimaryType(KnownPrimaryType.Stream)) - { - imports.Add("okhttp3.RequestBody"); - imports.Add("okhttp3.MediaType"); - } - if (parameter.Location != ParameterLocation.Body - && parameter.Location != ParameterLocation.None) + if (type == null) { - if (type.IsPrimaryType(KnownPrimaryType.ByteArray) || - type.Name == "ByteArray") - { - imports.Add("org.apache.commons.codec.binary.Base64"); - } - if (sequenceType != null) - { - imports.Add("com.microsoft.rest.serializer.CollectionFormat"); - } + return new List(); } - - return imports; + return ((ITypeModel) type).Imports; } public static string ImportFrom(this HttpMethod httpMethod) @@ -190,32 +105,5 @@ public static string ImportFrom(this HttpMethod httpMethod) return package + httpMethod.ToString().ToUpper(CultureInfo.InvariantCulture); } } - - public static string ImportFrom(this ParameterLocation parameterLocation) - { - if (parameterLocation == ParameterLocation.FormData) - { - return "retrofit2.http.Part"; - } - else if (parameterLocation != ParameterLocation.None) - { - return "retrofit2.http." + parameterLocation.ToString(); - } - else - { - return null; - } - } - - public static IEnumerable ParseGenericType(this CompositeType type) - { - string name = type.Name; - string[] types = type.Name.Split(new String[]{"<", ">", ",", ", "}, StringSplitOptions.RemoveEmptyEntries); - foreach (var innerType in types.Where(t => !string.IsNullOrWhiteSpace(t))) { - if (!JavaCodeNamer.PrimaryTypes.Contains(innerType.Trim())) { - yield return new CompositeType() { Name = innerType.Trim() }; - } - } - } } } diff --git a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs index 061a6e9f8b865..9273ec6f370ce 100644 --- a/AutoRest/Generators/Java/Java/GlobalSuppressions.cs +++ b/AutoRest/Generators/Java/Java/GlobalSuppressions.cs @@ -144,3 +144,43 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getDateTime", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "DateTime", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ResponseGeneration")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#converToClientType(Microsoft.Rest.Generator.ClientModel.IType,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.CompositeTypeModel.#_package")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.CompositeTypeModel.#_runtimePackage")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.CompositeTypeModel.#.ctor(System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.CompositeTypeModel.#.ctor(System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.EnumTypeModel.#.ctor(Microsoft.Rest.Generator.ClientModel.EnumType,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.EnumTypeModel.#.ctor(Microsoft.Rest.Generator.ClientModel.EnumType,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1716:IdentifiersShouldNotMatchKeywords", MessageId = "Imports", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ITypeModel.#Imports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeGenerator.#.ctor(Microsoft.Rest.Generator.Settings)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#_package")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#.ctor(System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#.ctor(System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#NormalizeTypeReference(Microsoft.Rest.Generator.ClientModel.IType)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.JavaCodeNamer.#NormalizeCompositeType(Microsoft.Rest.Generator.ClientModel.CompositeType)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ParameterModels")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#LogicalParameterModels")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ModelTemplateModel.#.ctor(Microsoft.Rest.Generator.ClientModel.CompositeType,Microsoft.Rest.Generator.ClientModel.ServiceClient)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#LocationImport(Microsoft.Rest.Generator.ClientModel.ParameterLocation)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#NeedsSpecialSerialization(Microsoft.Rest.Generator.ClientModel.IType)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_response")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ModelTemplateModel.#PropertyModels")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "1", Scope = "member", Target = "Microsoft.Rest.Generator.Java.PropertyModel.#.ctor(Microsoft.Rest.Generator.ClientModel.Property,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.Java.PropertyModel.#.ctor(Microsoft.Rest.Generator.ClientModel.Property,System.String)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#convertClientTypeToWireType(Microsoft.Rest.Generator.Java.ITypeModel,System.String,System.String,System.String,System.Int32)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#convertClientTypeToWireType(Microsoft.Rest.Generator.Java.ITypeModel,System.String,System.String,System.String,System.Int32)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_interfaceImports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_interfaceImports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1002:DoNotExposeGenericLists", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_implImports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1051:DoNotDeclareVisibleInstanceFields", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#_implImports")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.Append(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ResponseModel.#convertToClientType(Microsoft.Rest.Generator.Java.ITypeModel,System.String,System.String,System.Int32)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#BuildInputMappings(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#BuildInputMappings(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#ResponseGeneration(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "getBody", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.MethodTemplateModel.#SuccessCallback(System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)", Scope = "member", Target = "Microsoft.Rest.Generator.Java.ParameterModel.#convertClientTypeToWireType(Microsoft.Rest.Generator.Java.ITypeModel,System.String,System.String,System.String,System.Int32)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", MessageId = "0", Scope = "member", Target = "Microsoft.Rest.Generator.Java.PrimaryTypeModel.#DefaultValue(Microsoft.Rest.Generator.ClientModel.Method)")] diff --git a/AutoRest/Generators/Java/Java/JavaCodeGenerator.cs b/AutoRest/Generators/Java/Java/JavaCodeGenerator.cs index a40e506870426..275c4b16eb4e3 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeGenerator.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeGenerator.cs @@ -21,7 +21,7 @@ public class JavaCodeGenerator : CodeGenerator public JavaCodeGenerator(Settings settings) : base(settings) { - Namer = new JavaCodeNamer(); + Namer = new JavaCodeNamer(settings.Namespace); } public override string Name diff --git a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs index af18dbb59f6b1..c8d58b1031848 100644 --- a/AutoRest/Generators/Java/Java/JavaCodeNamer.cs +++ b/AutoRest/Generators/Java/Java/JavaCodeNamer.cs @@ -14,7 +14,7 @@ namespace Microsoft.Rest.Generator.Java { public class JavaCodeNamer : CodeNamer { - private readonly HashSet _normalizedTypes; + private Dictionary _visited = new Dictionary(); public const string ExternalExtension = "x-ms-external"; @@ -22,15 +22,18 @@ public class JavaCodeNamer : CodeNamer public static HashSet JavaBuiltInTypes { get; private set; } + protected string _package; + #region constructor /// /// Initializes a new instance of CSharpCodeNamingFramework. /// - public JavaCodeNamer() + public JavaCodeNamer(string nameSpace) { // List retrieved from // http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html + _package = nameSpace.ToLower(CultureInfo.InvariantCulture); new HashSet { "abstract", "assert", "boolean", "break", "byte", @@ -47,7 +50,6 @@ public JavaCodeNamer() "period", "stream", "string", "object", "header" }.ForEach(s => ReservedWords.Add(s)); - _normalizedTypes = new HashSet(); PrimaryTypes = new HashSet(); new HashSet { @@ -209,6 +211,7 @@ protected override void NormalizeParameters(Method method) { parameterTransformation.OutputParameter.Name = method.Scope.GetUniqueName(GetParameterName(parameterTransformation.OutputParameter.GetClientName())); parameterTransformation.OutputParameter.Type = NormalizeTypeReference(parameterTransformation.OutputParameter.Type); + parameterTransformation.OutputParameter = new ParameterModel(parameterTransformation.OutputParameter, method); QuoteParameter(parameterTransformation.OutputParameter); @@ -244,6 +247,11 @@ protected override void NormalizeClientProperties(ServiceClient client) } } } + public override Response NormalizeTypeReference(Response typePair) + { + return new Response((ITypeModel) NormalizeTypeReference(typePair.Body), + (ITypeModel) NormalizeTypeReference(typePair.Headers)); + } public override IType NormalizeTypeDeclaration(IType type) { @@ -259,35 +267,42 @@ public override IType NormalizeTypeReference(IType type) var enumType = type as EnumType; if (enumType != null && enumType.ModelAsString) { - type = new PrimaryType(KnownPrimaryType.String); + type = new PrimaryTypeModel(KnownPrimaryType.String); } - // Using Any instead of Contains since object hash is bound to a property which is modified during normalization - if (_normalizedTypes.Any(item => type.Equals(item))) + if (_visited.ContainsKey(type)) { - return _normalizedTypes.First(item => type.Equals(item)); + return _visited[type]; } - _normalizedTypes.Add(type); if (type is PrimaryType) { - return NormalizePrimaryType(type as PrimaryType); + _visited[type] = new PrimaryTypeModel(type as PrimaryType); + return _visited[type]; } if (type is SequenceType) { - return NormalizeSequenceType(type as SequenceType); + SequenceTypeModel model = new SequenceTypeModel(type as SequenceType); + _visited[type] = model; + return NormalizeSequenceType(model); } if (type is DictionaryType) { - return NormalizeDictionaryType(type as DictionaryType); + DictionaryTypeModel model = new DictionaryTypeModel(type as DictionaryType); + _visited[type] = model; + return NormalizeDictionaryType(model); } if (type is CompositeType) { - return NormalizeCompositeType(type as CompositeType); + CompositeTypeModel model = NewCompositeTypeModel(type as CompositeType); + _visited[type] = model; + return NormalizeCompositeType(model); } if (type is EnumType) { - return NormalizeEnumType(type as EnumType); + EnumTypeModel model = new EnumTypeModel(type as EnumType, _package); + _visited[type] = model; + return NormalizeEnumType(model); } @@ -313,7 +328,12 @@ private IType NormalizeEnumType(EnumType enumType) return enumType; } - private IType NormalizeCompositeType(CompositeType compositeType) + protected virtual CompositeTypeModel NewCompositeTypeModel(CompositeType compositeType) + { + return new CompositeTypeModel(compositeType as CompositeType, _package); + } + + protected virtual IType NormalizeCompositeType(CompositeType compositeType) { compositeType.Name = GetTypeName(compositeType.Name); @@ -330,75 +350,14 @@ private IType NormalizeCompositeType(CompositeType compositeType) return compositeType; } - private static PrimaryType NormalizePrimaryType(PrimaryType primaryType) + public static PrimaryTypeModel NormalizePrimaryType(PrimaryType primaryType) { if (primaryType == null) { throw new ArgumentNullException("primaryType"); } - if (primaryType.Type == KnownPrimaryType.Boolean) - { - primaryType.Name = "boolean"; - } - else if (primaryType.Type == KnownPrimaryType.ByteArray) - { - primaryType.Name = "byte[]"; - } - else if (primaryType.Type == KnownPrimaryType.Date) - { - primaryType.Name = "LocalDate"; - } - else if (primaryType.Type == KnownPrimaryType.DateTime) - { - primaryType.Name = "DateTime"; - } - else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123) - { - primaryType.Name = "DateTimeRfc1123"; - } - else if (primaryType.Type == KnownPrimaryType.Double) - { - primaryType.Name = "double"; - } - else if (primaryType.Type == KnownPrimaryType.Decimal) - { - primaryType.Name = "BigDecimal"; - } - else if (primaryType.Type == KnownPrimaryType.Int) - { - primaryType.Name = "int"; - } - else if (primaryType.Type == KnownPrimaryType.Long) - { - primaryType.Name = "long"; - } - else if (primaryType.Type == KnownPrimaryType.Stream) - { - primaryType.Name = "InputStream"; - } - else if (primaryType.Type == KnownPrimaryType.String) - { - primaryType.Name = "String"; - } - else if (primaryType.Type == KnownPrimaryType.TimeSpan) - { - primaryType.Name = "Period"; - } - else if (primaryType.Type == KnownPrimaryType.Uuid) - { - primaryType.Name = "UUID"; - } - else if (primaryType.Type == KnownPrimaryType.Object) - { - primaryType.Name = "Object"; - } - else if (primaryType.Type == KnownPrimaryType.Credentials) - { - primaryType.Name = "ServiceClientCredentials"; - } - - return primaryType; + return new PrimaryTypeModel(primaryType); } private IType NormalizeSequenceType(SequenceType sequenceType) @@ -456,113 +415,6 @@ public static IType WrapPrimitiveType(IType type) } } - public static IEnumerable ImportPrimaryType(PrimaryType primaryType) - { - if (primaryType == null) - { - yield break; - } - - if (primaryType.Type == KnownPrimaryType.Date || - primaryType.Name == "LocalDate") - { - yield return "org.joda.time.LocalDate"; - } - else if (primaryType.Type == KnownPrimaryType.DateTime || - primaryType.Name == "DateTime") - { - yield return "org.joda.time.DateTime"; - } - else if (primaryType.Type == KnownPrimaryType.Decimal || - primaryType.Name == "Decimal") - { - yield return "java.math.BigDecimal"; - } - else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123 || - primaryType.Name == "DateTimeRfc1123") - { - yield return "com.microsoft.rest.DateTimeRfc1123"; - yield return "org.joda.time.DateTime"; - } - else if (primaryType.Type == KnownPrimaryType.Stream || - primaryType.Name == "InputStream") - { - yield return "java.io.InputStream"; - } - else if (primaryType.Type == KnownPrimaryType.TimeSpan || - primaryType.Name == "Period") - { - yield return "org.joda.time.Period"; - } - else if (primaryType.Type == KnownPrimaryType.Uuid || primaryType.Name == "Uuid") - { - yield return "java.util.UUID"; - } - else - { - yield break; - } - } - - public virtual List ImportType(IType type, string ns) - { - List imports = new List(); - var sequenceType = type as SequenceType; - var dictionaryType = type as DictionaryType; - var primaryType = type as PrimaryType; - var compositeType = type as CompositeType; - if (sequenceType != null) - { - imports.Add("java.util.List"); - imports.AddRange(ImportType(sequenceType.ElementType, ns)); - } - else if (dictionaryType != null) - { - imports.Add("java.util.Map"); - imports.AddRange(ImportType(dictionaryType.ValueType, ns)); - } - else if (compositeType != null && ns != null) - { - if (type.Name.Contains('<')) - { - imports.AddRange(compositeType.ParseGenericType().SelectMany(t => ImportType(t, ns))); - } - else if (compositeType.Extensions.ContainsKey(ExternalExtension) && - (bool)compositeType.Extensions[ExternalExtension]) - { - imports.Add(string.Join( - ".", - "com.microsoft.rest", - type.Name)); - } - else - { - imports.Add(string.Join( - ".", - ns.ToLower(CultureInfo.InvariantCulture), - "models", - type.Name)); - } - } - else if (type is EnumType && ns != null) - { - imports.Add(string.Join( - ".", - ns.ToLower(CultureInfo.InvariantCulture), - "models", - type.Name)); - } - else if (primaryType != null) - { - var importedFrom = JavaCodeNamer.ImportPrimaryType(primaryType); - if (importedFrom != null) - { - imports.AddRange(importedFrom); - } - } - return imports; - } - public static string GetJavaException(string exception, ServiceClient serviceClient) { switch (exception) { diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index 4c613a265e16f..c9f8bc6faf9fa 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -9,19 +9,23 @@ using System.Globalization; using System.Text; using System; +using System.Net; namespace Microsoft.Rest.Generator.Java { public class MethodTemplateModel : Method { - private JavaCodeNamer _namer; + private ResponseModel _returnTypeModel; + private Dictionary _responseModels; public MethodTemplateModel(Method source, ServiceClient serviceClient) { this.LoadFrom(source); - ParameterTemplateModels = new List(); - source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p))); - source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => ParameterTemplateModels.Add(new ParameterTemplateModel(p))); + ParameterModels = new List(); + LogicalParameterModels = new List(); + source.Parameters.Where(p => p.Location == ParameterLocation.Path).ForEach(p => ParameterModels.Add(new ParameterModel(p, this))); + source.Parameters.Where(p => p.Location != ParameterLocation.Path).ForEach(p => ParameterModels.Add(new ParameterModel(p, this))); + source.LogicalParameters.ForEach(p => LogicalParameterModels.Add(new ParameterModel(p, this))); ServiceClient = serviceClient; if (source.Group != null) { @@ -33,15 +37,9 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) OperationName = serviceClient.Name; ClientReference = "this"; } - _namer = new JavaCodeNamer(); - } - - protected virtual JavaCodeNamer Namer - { - get - { - return _namer; - } + _returnTypeModel = new ResponseModel(ReturnType); + _responseModels = new Dictionary(); + Responses.ForEach(r => _responseModels.Add(r.Key, new ResponseModel(r.Value))); } public string ClientReference { get; set; } @@ -50,18 +48,36 @@ protected virtual JavaCodeNamer Namer public ServiceClient ServiceClient { get; set; } - public List ParameterTemplateModels { get; private set; } + public List ParameterModels { get; private set; } - public IEnumerable RetrofitParameters + public List LogicalParameterModels { get; private set; } + + public virtual ResponseModel ReturnTypeModel { get { - return LogicalParameters.Where(p => p.Location != ParameterLocation.None) + return _returnTypeModel; + } + } + + public virtual Dictionary ResponseModels + { + get + { + return _responseModels; + } + } + + public IEnumerable RetrofitParameters + { + get + { + return LogicalParameterModels.Where(p => p.Location != ParameterLocation.None) .Where(p => !p.Extensions.ContainsKey("hostParameter")); } } - public IEnumerable OrderedRetrofitParameters + public IEnumerable OrderedRetrofitParameters { get { @@ -107,24 +123,7 @@ public virtual string MethodParameterApiDeclaration parameter.SerializedName)); } var declarativeName = parameter.ClientProperty != null ? parameter.ClientProperty.Name : parameter.Name; - if (parameter.Type.IsPrimaryType(KnownPrimaryType.Stream)) - { - declarationBuilder.Append("RequestBody"); - } - else if ((parameter.Location != ParameterLocation.Body) - && parameter.Type.NeedsSpecialSerialization()) - { - declarationBuilder.Append("String"); - } - else - { - string typeString = parameter.Type.Name; - if (!parameter.IsRequired) - { - typeString = JavaCodeNamer.WrapPrimitiveType(parameter.Type).Name; - } - declarationBuilder.Append(typeString); - } + declarationBuilder.Append(parameter.WireType.Name); declarationBuilder.Append(" " + declarativeName); declarations.Add(declarationBuilder.ToString()); } @@ -141,14 +140,7 @@ public virtual string MethodParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant)) { - if (parameter.Type.IsPrimaryType(KnownPrimaryType.Stream)) - { - declarations.Add("byte[] " + parameter.Name); - } - else - { - declarations.Add(parameter.Type.UserHandledType().ToString() + " " + parameter.Name); - } + declarations.Add(parameter.ClientType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -163,7 +155,7 @@ public virtual string MethodRequiredParameterDeclaration List declarations = new List(); foreach (var parameter in LocalParameters.Where(p => !p.IsConstant && p.IsRequired)) { - declarations.Add(parameter.Type.UserHandledType().ToString() + " " + parameter.Name); + declarations.Add(parameter.ClientType.ParameterVariant + " " + parameter.Name); } var declaration = string.Join(", ", declarations); @@ -186,73 +178,87 @@ public string MethodParameterInvocation } } - public string MethodParameterApiInvocation + public string MethodRequiredParameterInvocation { get { - List declarations = new List(); - foreach (var parameter in OrderedRetrofitParameters) + List invocations = new List(); + foreach (var parameter in LocalParameters) { - if ((parameter.Location != ParameterLocation.Body) - && parameter.Type.NeedsSpecialSerialization()) - { - declarations.Add(parameter.ToString(parameter.Name, ClientReference)); - } - else if (parameter.Type.UserHandledType() != parameter.Type) + if (parameter.IsRequired) { - declarations.Add(string.Format(CultureInfo.InvariantCulture, "new {0}({1})", parameter.Type.Name, parameter.Name)); - } - else if (parameter.Type.IsPrimaryType(KnownPrimaryType.Stream)) - { - declarations.Add(string.Format(CultureInfo.InvariantCulture, - "RequestBody.create(MediaType.parse(\"{0}\"), {1})", - RequestContentType, parameter.Name)); + invocations.Add(parameter.Name); } else { - declarations.Add(parameter.Name); + invocations.Add("null"); } } - var declaration = string.Join(", ", declarations); + var declaration = string.Join(", ", invocations); return declaration; } } - public string MethodParameterApiInvocationWithCallback + public string MethodParameterApiInvocation { get { - var parameters = MethodParameterApiInvocation; - if (!parameters.IsNullOrEmpty()) + List invocations = new List(); + foreach (var parameter in OrderedRetrofitParameters) { - parameters += ", "; + invocations.Add(parameter.WireName); } - parameters += string.Format(CultureInfo.InvariantCulture, "new ServiceResponseCallback()"); - return parameters; + + var declaration = string.Join(", ", invocations); + return declaration; } } - public string LocalMethodParameterInvocation + public string MethodRequiredParameterApiInvocation { get { - List declarations = new List(); - foreach (var parameter in LocalParameters) + List invocations = new List(); + foreach (var parameter in OrderedRetrofitParameters) + { + invocations.Add(parameter.WireName); + } + + var declaration = string.Join(", ", invocations); + return declaration; + } + } + + public string ParameterConversion + { + get + { + IndentedStringBuilder builder = new IndentedStringBuilder(); + foreach (var p in RetrofitParameters) { - if ((parameter.Location != ParameterLocation.Body) - && parameter.Type.NeedsSpecialSerialization()) + if (p.NeedsConversion) { - declarations.Add(parameter.ToString(parameter.Name, ClientReference)); + builder.Append(p.ConvertToWireType(p.Name, ClientReference)); } - else + } + return builder.ToString(); + } + } + + public string RequiredParameterConversion + { + get + { + IndentedStringBuilder builder = new IndentedStringBuilder(); + foreach (var p in RetrofitParameters.Where(p => p.IsRequired)) + { + if (p.NeedsConversion) { - declarations.Add(parameter.Name); + builder.Append(p.ConvertToWireType(p.Name, ClientReference)); } } - - var declaration = string.Join(", ", declarations); - return declaration; + return builder.ToString(); } } @@ -260,17 +266,17 @@ public string LocalMethodParameterInvocation /// Generates input mapping code block. /// /// - public virtual string BuildInputMappings() + public virtual string BuildInputMappings(bool filterRequired = false) { var builder = new IndentedStringBuilder(); foreach (var transformation in InputParameterTransformation) { var nullCheck = BuildNullCheckExpression(transformation); - bool conditionalAssignment = !string.IsNullOrEmpty(nullCheck) && !transformation.OutputParameter.IsRequired; + bool conditionalAssignment = !string.IsNullOrEmpty(nullCheck) && !transformation.OutputParameter.IsRequired && !filterRequired; if (conditionalAssignment) { builder.AppendLine("{0} {1} = null;", - JavaCodeNamer.WrapPrimitiveType(transformation.OutputParameter.Type).Name, + ((ParameterModel) transformation.OutputParameter).ClientType.ParameterVariant, transformation.OutputParameter.Name); builder.AppendLine("if ({0}) {{", nullCheck).Indent(); } @@ -279,18 +285,29 @@ public virtual string BuildInputMappings() transformation.OutputParameter.Type is CompositeType) { builder.AppendLine("{0}{1} = new {2}();", - !conditionalAssignment ? transformation.OutputParameter.Type.Name + " " : "", + !conditionalAssignment ? ((ParameterModel)transformation.OutputParameter).ClientType.ParameterVariant + " " : "", transformation.OutputParameter.Name, transformation.OutputParameter.Type.Name); } foreach (var mapping in transformation.ParameterMappings) { - builder.AppendLine("{0}{1}{2};", - !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? - transformation.OutputParameter.Type.Name + " " : "", - transformation.OutputParameter.Name, - GetMapping(mapping)); + if (filterRequired && !mapping.InputParameter.IsRequired) + { + builder.AppendLine("{0}{1}{2};", + !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? + ((ParameterModel)transformation.OutputParameter).WireType + " " : "", + ((ParameterModel)transformation.OutputParameter).WireName, + " = " + ((ParameterModel)transformation.OutputParameter).WireType.DefaultValue(this)); + } + else + { + builder.AppendLine("{0}{1}{2};", + !conditionalAssignment && !(transformation.OutputParameter.Type is CompositeType) ? + ((ParameterModel)transformation.OutputParameter).ClientType.ParameterVariant + " " : "", + transformation.OutputParameter.Name, + GetMapping(mapping)); + } } if (conditionalAssignment) @@ -336,11 +353,11 @@ private static string BuildNullCheckExpression(ParameterTransformation transform .Select(m => m.InputParameter.Name + " != null")); } - public IEnumerable RequiredNullableParameters + public IEnumerable RequiredNullableParameters { get { - foreach (var param in ParameterTemplateModels) + foreach (var param in ParameterModels) { if (!param.Type.IsPrimaryType(KnownPrimaryType.Int) && !param.Type.IsPrimaryType(KnownPrimaryType.Double) && @@ -354,11 +371,11 @@ public IEnumerable RequiredNullableParameters } } - public IEnumerable ParametersToValidate + public IEnumerable ParametersToValidate { get { - foreach (var param in ParameterTemplateModels) + foreach (var param in ParameterModels) { if (param.Type is PrimaryType || param.Type is EnumType || @@ -409,7 +426,7 @@ public virtual string MethodParameterDeclarationWithCallback parameters += ", "; } parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", - GenericReturnTypeString); + ReturnTypeModel.GenericBodyClientTypeString); return parameters; } } @@ -424,7 +441,7 @@ public virtual string MethodRequiredParameterDeclarationWithCallback parameters += ", "; } parameters += string.Format(CultureInfo.InvariantCulture, "final ServiceCallback<{0}> serviceCallback", - GenericReturnTypeString); + ReturnTypeModel.GenericBodyClientTypeString); return parameters; } } @@ -443,16 +460,30 @@ public virtual string MethodParameterInvocationWithCallback } } + public virtual string MethodRequiredParameterInvocationWithCallback + { + get + { + var parameters = MethodRequiredParameterInvocation; + if (!parameters.IsNullOrEmpty()) + { + parameters += ", "; + } + parameters += "serviceCallback"; + return parameters; + } + } + /// /// Get the parameters that are actually method parameters in the order they appear in the method signature /// exclude global parameters /// - public IEnumerable LocalParameters + public IEnumerable LocalParameters { get { //Omit parameter-group properties for now since Java doesn't support them yet - return ParameterTemplateModels.Where( + return ParameterModels.Where( p => p != null && p.ClientProperty == null && !string.IsNullOrWhiteSpace(p.Name)) .OrderBy(item => !item.IsRequired); } @@ -521,103 +552,6 @@ public virtual List ExceptionStatements } } - /// - /// Get the type name for the method's return type - /// - public string ReturnTypeString - { - get - { - if (ReturnType.Body != null) - { - return JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).Name; - } - return "void"; - } - } - - public virtual string GenericReturnTypeString - { - get - { - if (ReturnType.Body != null) - { - return JavaCodeNamer.WrapPrimitiveType(ReturnType.Body.UserHandledType()).Name; - } - return "Void"; - } - } - - public virtual string CallbackGenericTypeString - { - get - { - return GenericReturnTypeString; - } - } - - public virtual string DelegateReturnTypeString - { - get - { - if (ReturnType.Body != null) - { - return JavaCodeNamer.WrapPrimitiveType(ReturnType.Body).Name; - } - return "Void"; - } - } - - public virtual string TypeTokenType(IType type) - { - return JavaCodeNamer.WrapPrimitiveType(type).Name; - } - - public string OperationResponseType - { - get - { - if (ReturnType.Headers == null) - { - return "ServiceResponse"; - } - else - { - return "ServiceResponseWithHeaders"; - } - } - } - - public string OperationResponseReturnTypeString - { - get - { - if (ReturnType.Headers == null) - { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", OperationResponseType, GenericReturnTypeString); - } - else - { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", OperationResponseType, GenericReturnTypeString, ReturnType.Headers.Name); - } - } - } - - public virtual string DelegateOperationResponseReturnTypeString - { - get - { - if (ReturnType.Headers == null) - { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", OperationResponseType, DelegateReturnTypeString); - } - else - { - return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", OperationResponseType, DelegateReturnTypeString, ReturnType.Headers.Name); - } - } - } - public string CallType { get @@ -664,58 +598,48 @@ public virtual string RuntimeBasePackage } } - public virtual string ResponseGeneration + public virtual string ResponseGeneration(bool filterRequired = false) { - get + if (ReturnTypeModel.NeedsConversion) { - var userType = ReturnType.Body.UserHandledType(); - if (ReturnType.Body != userType) - { - userType = JavaCodeNamer.WrapPrimitiveType(userType); - IndentedStringBuilder builder= new IndentedStringBuilder(); - builder.AppendLine("ServiceResponse<{0}> response = {1}Delegate(call.execute());", - DelegateReturnTypeString, this.Name.ToCamelCase()); - builder.AppendLine("{0} body = null;", userType.Name) - .AppendLine("if (response.getBody() != null) {") - .Indent().AppendLine("body = response.getBody().get{0}();", userType.Name) - .Outdent().AppendLine("}"); - return builder.ToString(); - } - return ""; + IndentedStringBuilder builder= new IndentedStringBuilder(); + builder.AppendLine("ServiceResponse<{0}> response = {1}Delegate(call.execute());", + ReturnTypeModel.GenericBodyWireTypeString, this.Name.ToCamelCase()); + builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType.Name) + .AppendLine("if (response.getBody() != null) {") + .Indent().AppendLine("{0}", ReturnTypeModel.ConvertBodyToClientType("response.getBody()", "body")) + .Outdent().AppendLine("}"); + return builder.ToString(); } + return ""; } public virtual string ReturnValue { get { - if (ReturnType.Body.UserHandledType() != ReturnType.Body) + if (ReturnTypeModel.NeedsConversion) { - return "new ServiceResponse<" + this.GenericReturnTypeString + ">(body, response.getResponse())"; + return "new ServiceResponse<" + ReturnTypeModel.GenericBodyClientTypeString + ">(body, response.getResponse())"; } return this.Name + "Delegate(call.execute())"; } } - public virtual string SuccessCallback + public virtual string SuccessCallback(bool filterRequired = false) { - get + if (ReturnTypeModel.NeedsConversion) { - var userType = ReturnType.Body.UserHandledType(); - if (ReturnType.Body != userType) - { - userType = JavaCodeNamer.WrapPrimitiveType(userType); - IndentedStringBuilder builder = new IndentedStringBuilder(); - builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", DelegateReturnTypeString, this.Name); - builder.AppendLine("{0} body = null;", userType.Name) - .AppendLine("if (result.getBody() != null) {") - .Indent().AppendLine("body = result.getBody().get{0}();", userType.Name) - .Outdent().AppendLine("}"); - builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", GenericReturnTypeString); - return builder.ToString(); - } - return string.Format(CultureInfo.InvariantCulture, "serviceCallback.success({0}Delegate(response));", this.Name); + IndentedStringBuilder builder = new IndentedStringBuilder(); + builder.AppendLine("ServiceResponse<{0}> result = {1}Delegate(response);", ReturnTypeModel.GenericBodyWireTypeString, this.Name); + builder.AppendLine("{0} body = null;", ReturnTypeModel.BodyClientType) + .AppendLine("if (result.getBody() != null) {") + .Indent().AppendLine("{0}", ReturnTypeModel.ConvertBodyToClientType("result.getBody()", "body")) + .Outdent().AppendLine("}"); + builder.AppendLine("serviceCallback.success(new ServiceResponse<{0}>(body, result.getResponse()));", ReturnTypeModel.GenericBodyClientTypeString); + return builder.ToString(); } + return string.Format(CultureInfo.InvariantCulture, "serviceCallback.success({0}Delegate(response));", this.Name); } public virtual string ServiceCallConstruction @@ -741,20 +665,12 @@ public virtual List InterfaceImports HashSet imports = new HashSet(); // static imports imports.Add("com.microsoft.rest.ServiceCall"); - imports.Add("com.microsoft.rest." + OperationResponseType); + imports.Add("com.microsoft.rest." + ReturnTypeModel.ClientResponseType); imports.Add("com.microsoft.rest.ServiceCallback"); // parameter types - this.Parameters.ForEach(p => imports.AddRange(p.Type.ImportFrom(ServiceClient.Namespace, Namer))); + this.ParameterModels.ForEach(p => imports.AddRange(p.InterfaceImports)); // return type - imports.AddRange(this.ReturnType.Body.ImportFrom(ServiceClient.Namespace, Namer)); - if (Parameters.Any(p => p.Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - || ReturnType.Body.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123) - || ReturnType.Headers.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) - { - imports.Remove("com.microsoft.rest.DateTimeRfc1123"); - } - // Header type - imports.AddRange(this.ReturnType.Headers.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(this.ReturnTypeModel.InterfaceImports); // exceptions this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .ForEach(ex => { @@ -787,23 +703,10 @@ public virtual List ImplImports imports.Add("okhttp3.ResponseBody"); } imports.Add("com.microsoft.rest.ServiceCall"); - imports.Add("com.microsoft.rest." + OperationResponseType); + imports.Add("com.microsoft.rest." + ReturnTypeModel.ClientResponseType); imports.Add(RuntimeBasePackage + "." + ResponseBuilder); imports.Add("com.microsoft.rest.ServiceCallback"); - // API parameters - this.RetrofitParameters - .Where(p => p.Location == ParameterLocation.Body - || !p.Type.NeedsSpecialSerialization()) - .ForEach(p => imports.AddRange(p.Type.ImportFrom(ServiceClient.Namespace, Namer))); - // parameter locations - this.RetrofitParameters.ForEach(p => - { - string locationImport = p.Location.ImportFrom(); - if (!string.IsNullOrEmpty(locationImport)) - { - imports.Add(p.Location.ImportFrom()); - } - }); + this.RetrofitParameters.ForEach(p => imports.AddRange(p.RetrofitImports)); // Http verb annotations imports.Add(this.HttpMethod.ImportFrom()); // response type conversion @@ -825,18 +728,17 @@ public virtual List ImplImports { imports.Add("com.microsoft.rest.ServiceResponseCallback"); } - // parameter types - this.LocalParameters.Concat(this.LogicalParameters) - .ForEach(p => imports.AddRange(p.Type.ImportFrom(ServiceClient.Namespace, Namer))); - // parameter utils - this.LocalParameters.Concat(this.LogicalParameters) - .ForEach(p => imports.AddRange(p.ImportFrom())); + // parameters + this.LocalParameters.Concat(this.LogicalParameterModels) + .ForEach(p => imports.AddRange(p.ImplImports)); // return type - imports.AddRange(this.ReturnType.Body.ImportFrom(ServiceClient.Namespace, Namer)); + imports.AddRange(this.ReturnTypeModel.ImplImports); + if (ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) + { + imports.Add("retrofit2.http.Streaming"); + } // response type (can be different from return type) - this.Responses.ForEach(r => imports.AddRange(r.Value.Body.ImportFrom(ServiceClient.Namespace, Namer))); - // Header type - imports.AddRange(this.ReturnType.Headers.ImportFrom(ServiceClient.Namespace, Namer)); + this.ResponseModels.ForEach(r => imports.AddRange(r.Value.ImplImports)); // exceptions this.ExceptionString.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries) .ForEach(ex => diff --git a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs index 715171fac30c8..a47aa6b345011 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/ModelTemplateModel.cs @@ -25,7 +25,9 @@ public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) { _parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } - _namer = new JavaCodeNamer(); + _namer = new JavaCodeNamer(serviceClient.Namespace); + PropertyModels = new List(); + Properties.ForEach(p => PropertyModels.Add(new PropertyModel(p, serviceClient.Namespace))); } protected virtual JavaCodeNamer Namer @@ -38,6 +40,8 @@ protected virtual JavaCodeNamer Namer public ServiceClient ServiceClient { get; set; } + public List PropertyModels { get; private set; } + public bool IsPolymorphic { get @@ -139,18 +143,11 @@ private bool isSpecial(IType type) public virtual IEnumerable ImportList { get { - HashSet classes = new HashSet(); - foreach (var property in this.Properties) + var classes = new HashSet(); + classes.AddRange(PropertyModels.SelectMany(pm => pm.Imports)); + if (this.Properties.Any(p => !p.GetJsonProperty().IsNullOrEmpty())) { - classes.AddRange(property.Type.ImportFrom(ServiceClient.Namespace, Namer) - .Where(c => !c.StartsWith( - string.Join(".", ServiceClient.Namespace, "models"), - StringComparison.OrdinalIgnoreCase))); - - if (this.Properties.Any(p => !p.GetJsonProperty().IsNullOrEmpty())) - { - classes.Add("com.fasterxml.jackson.annotation.JsonProperty"); - } + classes.Add("com.fasterxml.jackson.annotation.JsonProperty"); } // For polymorphism if (IsPolymorphic) @@ -167,7 +164,7 @@ public virtual IEnumerable ImportList { { classes.Add("com.microsoft.rest.serializer.JsonFlatten"); } - return classes.Distinct().AsEnumerable(); + return classes.AsEnumerable(); } } diff --git a/AutoRest/Generators/Java/Java/Templates/EnumTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/EnumTemplate.cshtml index 04e2020a27d58..d974f639c110e 100644 --- a/AutoRest/Generators/Java/Java/Templates/EnumTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/EnumTemplate.cshtml @@ -63,4 +63,10 @@ public enum @(Model.Name) { } return null; } + @EmptyLine + + @@Override + public String toString() { + return toValue(); + } } diff --git a/AutoRest/Generators/Java/Java/Templates/MethodGroupRetrofitTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodGroupRetrofitTemplate.cshtml index 164af9fa862f6..f53af2be734d2 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodGroupRetrofitTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodGroupRetrofitTemplate.cshtml @@ -27,6 +27,10 @@ else { @: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))") } +if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) +{ +@: @@Streaming +} @: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration); @EmptyLine } diff --git a/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml index fbc6a1d9a99f7..b2379b5e0115e 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodInterfaceTemplate.cshtml @@ -27,14 +27,14 @@ } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.ClientResponseType} if successful. } else { -@: * @@return the {@@link @Model.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.ClientResponseType} object if successful. } */ -@Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString; +@Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString; @EmptyLine /** @if (!string.IsNullOrEmpty(Model.Summary)) @@ -77,14 +77,14 @@ ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationWithCall } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.ClientResponseType} if successful. } else { -@: * @@return the {@@link @Model.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.ClientResponseType} object if successful. } */ -@Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString; +@Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString; @EmptyLine /** @if (!string.IsNullOrEmpty(Model.Summary)) diff --git a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml index c90a59e9b7f9c..10c86bd6adb4f 100644 --- a/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/MethodTemplate.cshtml @@ -27,14 +27,14 @@ } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.ClientResponseType} if successful. } else { -@: * @@return the {@@link @Model.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.ClientResponseType} object if successful. } */ -public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { +public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodRequiredParameterDeclaration) throws @Model.ExceptionString { @foreach (var param in Model.RequiredNullableParameters) { @: if (@param.Name == null) { @@ -45,19 +45,19 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodRequi { @: Validator.validate(@(param.Name)); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (!parameter.IsRequired) { -@: final @(parameter.Type.UserHandledType().Name) @(parameter.Name) = null; +@: final @(parameter.WireType.Name) @(parameter.WireName) = @(parameter.WireType.DefaultValue(Model)); } if (parameter.IsConstant) { -@: final @(parameter.Type.UserHandledType().Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } - @Model.BuildInputMappings() + @Model.BuildInputMappings(true) @if (Model.ServiceClient.Extensions.ContainsKey(Microsoft.Rest.Generator.Extensions.ParameterizedHostExtension)) { @@ -66,8 +66,9 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } - Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); - @Model.ResponseGeneration + @Model.RequiredParameterConversion + Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation); + @Model.ResponseGeneration(true) return @Model.ReturnValue; } @EmptyLine @@ -105,18 +106,18 @@ public ServiceCall @(Model.Name)Async(@Model.MethodRequiredParameterDeclarationW @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (!parameter.IsRequired) { -@: final @(parameter.Type.UserHandledType().Name) @(parameter.Name) = null; +@: final @(parameter.WireType.Name) @(parameter.WireName) = @(parameter.WireType.DefaultValue(Model)); } if (parameter.IsConstant) { -@: final @(parameter.Type.UserHandledType().Name) @(parameter.Name) = @(parameter.DefaultValue); +@: final @(parameter.ClientType.ParameterVariant) @(parameter.Name) = @(parameter.DefaultValue); } } - @Model.BuildInputMappings() + @Model.BuildInputMappings(true) @if (Model.ServiceClient.Extensions.ContainsKey(Microsoft.Rest.Generator.Extensions.ParameterizedHostExtension)) { @@ -125,13 +126,14 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } - Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); + @Model.RequiredParameterConversion + Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodRequiredParameterApiInvocation); @Model.ServiceCallConstruction - call.enqueue(new @Model.InternalCallback<@(Model.CallbackGenericTypeString)>(serviceCallback) { + call.enqueue(new @Model.InternalCallback<@(Model.ReturnTypeModel.ClientCallbackTypeString)>(serviceCallback) { @@Override public void onResponse(Call<@Model.CallType> call, Response<@Model.CallType> response) { try { - @Model.SuccessCallback + @Model.SuccessCallback(true) } catch (@Model.OperationExceptionTypeString | IOException exception) { serviceCallback.failure(exception); } @@ -162,14 +164,14 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host } @if (Model.ReturnType.Body != null) { -@: * @@return the @Model.ReturnTypeString.EscapeXmlComment() object wrapped in {@@link @Model.OperationResponseType} if successful. +@: * @@return the @Model.ReturnTypeModel.BodyClientType.Name.EscapeXmlComment() object wrapped in {@@link @Model.ReturnTypeModel.ClientResponseType} if successful. } else { -@: * @@return the {@@link @Model.OperationResponseType} object if successful. +@: * @@return the {@@link @Model.ReturnTypeModel.ClientResponseType} object if successful. } */ -public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { +public @Model.ReturnTypeModel.ClientResponseTypeString @(Model.Name)(@Model.MethodParameterDeclaration) throws @Model.ExceptionString { @foreach (var param in Model.RequiredNullableParameters) { @: if (@param.Name == null) { @@ -180,7 +182,7 @@ public @Model.OperationResponseReturnTypeString @(Model.Name)(@Model.MethodParam { @: Validator.validate(@(param.Name)); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (parameter.IsConstant) { @@ -196,8 +198,9 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } + @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); - @Model.ResponseGeneration + @Model.ResponseGeneration() return @Model.ReturnValue; } @EmptyLine @@ -235,7 +238,7 @@ public ServiceCall @(Model.Name)Async(@Model.MethodParameterDeclarationWithCallb @: Validator.validate(@(param.Name), serviceCallback); } -@foreach (ParameterTemplateModel parameter in Model.LocalParameters) +@foreach (ParameterModel parameter in Model.LocalParameters) { if (parameter.IsConstant) { @@ -251,13 +254,14 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host @: @(Model.ClientReference).getBaseUrl().set("{@(param.SerializedName)}", @param.Name); } } + @Model.ParameterConversion Call<@Model.CallType> call = service.@(Model.Name)(@Model.MethodParameterApiInvocation); @Model.ServiceCallConstruction - call.enqueue(new @Model.InternalCallback<@(Model.CallbackGenericTypeString)>(serviceCallback) { + call.enqueue(new @Model.InternalCallback<@(Model.ReturnTypeModel.ClientCallbackTypeString)>(serviceCallback) { @@Override public void onResponse(Call<@Model.CallType> call, Response<@Model.CallType> response) { try { - @Model.SuccessCallback + @Model.SuccessCallback() } catch (@Model.OperationExceptionTypeString | IOException exception) { serviceCallback.failure(exception); } @@ -266,12 +270,12 @@ foreach (var param in Model.Parameters.Where(p => p.Extensions.ContainsKey("host return serviceCall; } @EmptyLine -private @Model.DelegateOperationResponseReturnTypeString @(Model.Name)Delegate(Response<@Model.CallType> response) throws @Model.ExceptionString { - return new @Model.ResponseBuilder<@Model.DelegateReturnTypeString, @Model.OperationExceptionTypeString>(@(Model.ClientReference).getMapperAdapter()) -@foreach (var response in Model.Responses) +private @Model.ReturnTypeModel.WireResponseTypeString @(Model.Name)Delegate(Response<@Model.CallType> response) throws @Model.ExceptionString { + return new @Model.ResponseBuilder<@Model.ReturnTypeModel.GenericBodyWireTypeString, @Model.OperationExceptionTypeString>(@(Model.ClientReference).getMapperAdapter()) +@foreach (var response in Model.ResponseModels) { - @:.register(@((int)response.Key), new TypeToken<@Model.TypeTokenType(response.Value.Body)>() { }.getType()) + @:.register(@((int)response.Key), new TypeToken<@response.Value.GenericBodyWireTypeString>() { }.getType()) } @if (Model.DefaultResponse.Body != null) { diff --git a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml index deb64fca76b2e..8ae9ece254ac2 100644 --- a/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/ModelTemplate.cshtml @@ -1,5 +1,6 @@ @using System.Linq @using System.Collections.Generic +@using Microsoft.Rest.Generator.Java @using Microsoft.Rest.Generator.Utilities @using Microsoft.Rest.Generator.ClientModel @using Microsoft.Rest.Generator.Java.TemplateModels @@ -42,7 +43,7 @@ var type = types[i]; { @:@@JsonFlatten } -public class @(Model.Name)@(Model.BaseModelType != null ? " extends " + Model.BaseModelType.Name : "") { +public class @(Model.Name)@(Model.BaseModelType != null ? " extends " + Model.BaseModelType.Name.ToPascalCase() : "") { @foreach (var property in Model.Properties) { @: /** @@ -86,10 +87,13 @@ if (!jsonSetting.IsNullOrEmpty()) @: * @: * @@return the @property.Name value @: */ -@: public @property.Type.UserHandledType().Name get@(property.Name.ToPascalCase())() { -if (property.Type.UserHandledType() != property.Type) +@: public @(((ITypeModel)property.Type).ResponseVariant) get@(property.Name.ToPascalCase())() { +if (property.Type.Name != ((ITypeModel) property.Type).ResponseVariant.Name) { -@: return this.@(property.Name).get@(property.Type.UserHandledType().Name)(); +@: if (this.@(property.Name) == null) { +@: return null; +@: } +@: return this.@(property.Name).get@(((ITypeModel)property.Type).ResponseVariant)(); } else { @@ -104,8 +108,8 @@ if (!property.IsReadOnly) @: * @: * @@param @property.Name the @property.Name value to set @: */ -@: public void set@(property.Name.ToPascalCase())(@property.Type.UserHandledType().Name @property.Name) { -if (property.Type.UserHandledType() != property.Type) +@: public void set@(property.Name.ToPascalCase())(@(((ITypeModel)property.Type).ResponseVariant) @property.Name) { +if (property.Type.Name != ((ITypeModel)property.Type).ResponseVariant.Name) { @: this.@(property.Name) = new @(property.Type.Name)(@property.Name); } diff --git a/AutoRest/Generators/Java/Java/Templates/ServiceClientRetrofitTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/ServiceClientRetrofitTemplate.cshtml index bc17e7d092fa1..7c8432c6a7625 100644 --- a/AutoRest/Generators/Java/Java/Templates/ServiceClientRetrofitTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/ServiceClientRetrofitTemplate.cshtml @@ -27,6 +27,10 @@ else { @: @@@(method.HttpMethod.ToString().ToUpper())("@(method.Url.TrimStart('/'))") } +if (method.ReturnType.Body.IsPrimaryType(KnownPrimaryType.Stream)) +{ +@: @@Streaming +} @: Call<@method.CallType> @(method.Name)(@method.MethodParameterApiDeclaration); @EmptyLine } diff --git a/AutoRest/Generators/Java/Java/Templates/ServiceClientTemplate.cshtml b/AutoRest/Generators/Java/Java/Templates/ServiceClientTemplate.cshtml index d96fdae31b76c..cb2b13b88d8c3 100644 --- a/AutoRest/Generators/Java/Java/Templates/ServiceClientTemplate.cshtml +++ b/AutoRest/Generators/Java/Java/Templates/ServiceClientTemplate.cshtml @@ -131,7 +131,7 @@ else { @: if (this.credentials != null) @: { -@: this.credentials.applyCredentialsFilter(this.client); +@: this.credentials.applyCredentialsFilter(clientBuilder); @: } } super.initialize(); diff --git a/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs new file mode 100644 index 0000000000000..dae1d8ad4df3a --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/CompositeTypeModel.cs @@ -0,0 +1,105 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java +{ + public class CompositeTypeModel : CompositeType, ITypeModel + { + protected string _package; + public const string ExternalExtension = "x-ms-external"; + protected string _runtimePackage = "com.microsoft.rest"; + + public CompositeTypeModel(CompositeType compositeType, string package) + : this(package) + { + this.LoadFrom(compositeType); + } + + public CompositeTypeModel(string package) + : base() + { + this._package = package.ToLower(CultureInfo.InvariantCulture); + } + + public virtual string Package + { + get + { + if (Extensions.ContainsKey(ExternalExtension) && + (bool)Extensions[ExternalExtension]) { + return _runtimePackage; + } + else + { + return string.Join( + ".", + _package, + "models"); + } + } + } + + public ITypeModel ParameterVariant + { + get + { + return this; + } + } + + public ITypeModel ResponseVariant + { + get + { + return this; + } + } + + public string DefaultValue(Method method) + { + return "null"; + } + + public IEnumerable Imports + { + get + { + var imports = new List(); + if (Name.Contains('<')) + { + imports.AddRange(ParseGenericType().SelectMany(t => t.Imports)); + } + else + { + imports.Add(string.Join(".", Package, Name)); + } + return imports; + } + } + + public ITypeModel InstanceType() + { + return this; + } + + private IEnumerable ParseGenericType() + { + string name = Name; + string[] types = Name.Split(new String[] { "<", ">", ",", ", " }, StringSplitOptions.RemoveEmptyEntries); + foreach (var innerType in types.Where(t => !string.IsNullOrWhiteSpace(t))) + { + if (!JavaCodeNamer.PrimaryTypes.Contains(innerType.Trim())) + { + yield return new CompositeTypeModel(_package) { Name = innerType.Trim() }; + } + } + } + } +} diff --git a/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs new file mode 100644 index 0000000000000..f471e1783b919 --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/DictionaryTypeModel.cs @@ -0,0 +1,79 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; + +namespace Microsoft.Rest.Generator.Java +{ + public class DictionaryTypeModel : DictionaryType, ITypeModel + { + public DictionaryTypeModel(DictionaryType dictionaryType) + : base() + { + this.LoadFrom(dictionaryType); + } + + public ITypeModel ValueTypeModel + { + get + { + return (ITypeModel)this.ValueType; + } + } + + public ITypeModel ParameterVariant + { + get + { + if (ValueTypeModel.ParameterVariant != ValueTypeModel) + { + return new DictionaryTypeModel(new DictionaryType() + { + NameFormat = "Map", + ValueType = ValueTypeModel.ParameterVariant + }); + } + return this; + } + } + + public ITypeModel ResponseVariant + { + get + { + if (ValueTypeModel.ResponseVariant != ValueTypeModel) + { + return new DictionaryTypeModel(new DictionaryType() + { + NameFormat = "Map", + ValueType = ValueTypeModel.ResponseVariant + }); + } + return this; + } + } + + public string DefaultValue(Method method) + { + return "null"; + } + + public IEnumerable Imports + { + get + { + List imports = new List { "java.util.Map" }; + return imports.Concat(((ITypeModel) this.ValueType).Imports); + } + } + + public ITypeModel InstanceType() + { + return this; + } + } +} diff --git a/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs new file mode 100644 index 0000000000000..aec50e5773d40 --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/EnumTypeModel.cs @@ -0,0 +1,58 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java +{ + public class EnumTypeModel : EnumType, ITypeModel + { + private string _package; + + public EnumTypeModel(EnumType enumType, string package) + : base() + { + this.LoadFrom(enumType); + this._package = package.ToLower(CultureInfo.InvariantCulture); + } + + public ITypeModel ParameterVariant + { + get + { + return this; + } + } + + public ITypeModel ResponseVariant + { + get + { + return this; + } + } + + public string DefaultValue(Method method) + { + return "null"; + } + + public IEnumerable Imports + { + get + { + yield return string.Join(".", _package, "models", Name); + } + } + + public ITypeModel InstanceType() + { + return this; + } + } +} diff --git a/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs new file mode 100644 index 0000000000000..5310d7dcba3bf --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/ITypeModel.cs @@ -0,0 +1,24 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; + +namespace Microsoft.Rest.Generator.Java +{ + public interface ITypeModel : IType + { + ITypeModel ParameterVariant { get; } + + ITypeModel ResponseVariant { get; } + + IEnumerable Imports { get; } + + ITypeModel InstanceType(); + + string DefaultValue(Method method); + } +} diff --git a/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs new file mode 100644 index 0000000000000..9dbfeca84a50d --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/ParameterModel.cs @@ -0,0 +1,257 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java +{ + public class ParameterModel : Parameter + { + private Method _method; + + public ParameterModel(Parameter parameter, Method method) + : base() + { + this.LoadFrom(parameter); + this._method = method; + // Use instance type for optional parameters + if (!this.IsRequired) + { + this.Type = ((ITypeModel) Type).InstanceType(); + } + _wireName = this.Name.ToCamelCase(); + if (NeedsConversion) + { + _wireName += "Converted"; + } + _implImports = new List(); + } + + public ITypeModel ClientType + { + get + { + return ((ITypeModel) Type).ParameterVariant; + } + } + + public ITypeModel WireType + { + get + { + if (Type.IsPrimaryType(KnownPrimaryType.Stream)) + { + return new PrimaryTypeModel(KnownPrimaryType.Stream) { Name = "RequestBody" }; + } + else if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData && NeedsSpecialSerialization(ClientType)) + { + return new PrimaryTypeModel(KnownPrimaryType.String); + } + else + { + return (ITypeModel) Type; + } + } + } + + private string _wireName; + + public string WireName + { + get + { + return _wireName; + } + } + + public bool NeedsConversion + { + get + { + return ClientType != WireType; + } + } + + public string ConvertToWireType(string source, string clientReference) + { + if (Location != ParameterLocation.Body && Location != ParameterLocation.FormData && NeedsSpecialSerialization(ClientType)) + { + var primary = ClientType as PrimaryTypeModel; + var sequence = ClientType as SequenceTypeModel; + if (primary != null && primary.IsPrimaryType(KnownPrimaryType.ByteArray)) + { + return string.Format(CultureInfo.InvariantCulture, "{0} {1} = Base64.encodeBase64String({2});", WireType.Name, _wireName, source); + } + else if (sequence != null) + { + return string.Format(CultureInfo.InvariantCulture, + "{0} {1} = {2}.getMapperAdapter().serializeList({3}, CollectionFormat.{4});", + WireType.Name, + _wireName, + clientReference, + source, + CollectionFormat.ToString().ToUpper(CultureInfo.InvariantCulture)); + } + } + + return convertClientTypeToWireType(WireType, source, _wireName, clientReference); + } + + private string convertClientTypeToWireType(ITypeModel wireType, string source, string target, string clientReference, int level = 0) + { + IndentedStringBuilder builder = new IndentedStringBuilder(); + if (wireType.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + if (!IsRequired) + { + builder.AppendLine("DateTimeRfc1123 {0} = {1};", target, wireType.DefaultValue(_method)) + .AppendLine("if ({0} != null) {{", source).Indent(); + } + builder.AppendLine("{0}{1} = new DateTimeRfc1123({2});", IsRequired ? "DateTimeRfc1123 " : "", target, source); + if (!IsRequired) + { + builder.Outdent().AppendLine("}"); + } + } + else if (wireType.IsPrimaryType(KnownPrimaryType.Stream)) + { + if (!IsRequired) + { + builder.AppendLine("RequestBody {0} = {1};", target, wireType.DefaultValue(_method)) + .AppendLine("if ({0} != null) {{", source).Indent(); + } + builder.AppendLine("{0}{1} = RequestBody.create(MediaType.parse(\"{2}\"), {3});", + IsRequired ? "RequestBody " : "", target, _method.RequestContentType, source); + if (!IsRequired) + { + builder.Outdent().AppendLine("}"); + } + } + else if (wireType is SequenceTypeModel) + { + if (!IsRequired) + { + builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.DefaultValue(_method)) + .AppendLine("if ({0} != null) {{", source).Indent(); + } + var sequenceType = wireType as SequenceTypeModel; + var elementType = sequenceType.ElementTypeModel; + var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + builder.AppendLine("{0}{1} = new ArrayList<{2}>();", IsRequired ? wireType.Name + " " : "" ,target, elementType.Name) + .AppendLine("for ({0} {1} : {2}) {{", elementType.ParameterVariant.Name, itemName, source) + .Indent().AppendLine(convertClientTypeToWireType(elementType, itemName, itemTarget, clientReference, level + 1)) + .AppendLine("{0}.add({1});", target, itemTarget) + .Outdent().Append("}"); + _implImports.Add("java.util.ArrayList"); + if (!IsRequired) + { + builder.Outdent().AppendLine("}"); + } + } + else if (wireType is DictionaryTypeModel) + { + if (!IsRequired) + { + builder.AppendLine("{0} {1} = {2};", WireType.Name, target, wireType.DefaultValue(_method)) + .AppendLine("if ({0} != null) {{", source).Indent(); + } + var dictionaryType = wireType as DictionaryTypeModel; + var valueType = dictionaryType.ValueTypeModel; + var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + builder.AppendLine("{0}{1} = new HashMap();", IsRequired ? wireType.Name + " " : "", target, valueType.Name) + .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.ParameterVariant.Name, itemName, source) + .Indent().AppendLine(convertClientTypeToWireType(valueType, itemName + ".getValue()", itemTarget, clientReference, level + 1)) + .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget) + .Outdent().Append("}"); + _implImports.Add("java.util.HashMap"); + if (!IsRequired) + { + builder.Outdent().AppendLine("}"); + } + } + return builder.ToString(); + } + + public IEnumerable InterfaceImports + { + get + { + return ClientType.Imports; + } + } + + public IEnumerable RetrofitImports + { + get + { + var imports = new List(); + // type imports + if (this.Location == ParameterLocation.Body || !NeedsSpecialSerialization(Type)) + { + imports.AddRange(WireType.Imports); + } + // parameter location + imports.Add(LocationImport(this.Location)); + return imports; + } + } + + private List _implImports; + + public IEnumerable ImplImports + { + get + { + var imports = new List(ClientType.Imports); + if (Location != ParameterLocation.Body) + { + if (this.Type.IsPrimaryType(KnownPrimaryType.ByteArray)) + { + imports.Add("org.apache.commons.codec.binary.Base64"); + } + else if (this.Type is SequenceType) + { + imports.Add("com.microsoft.rest.serializer.CollectionFormat"); + } + } + if (Type.IsPrimaryType(KnownPrimaryType.Stream) && Location == ParameterLocation.Body) + { + imports.Add("okhttp3.RequestBody"); + imports.Add("okhttp3.MediaType"); + } + return imports; + } + } + + private string LocationImport(ParameterLocation parameterLocation) + { + if (parameterLocation == ParameterLocation.FormData) + { + return "retrofit2.http.Part"; + } + else if (parameterLocation != ParameterLocation.None) + { + return "retrofit2.http." + parameterLocation.ToString(); + } + else + { + return null; + } + } + + private bool NeedsSpecialSerialization(IType type) + { + var known = type as PrimaryType; + return known != null && + type.IsPrimaryType(KnownPrimaryType.ByteArray) || + type is SequenceType; + } + } +} diff --git a/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs new file mode 100644 index 0000000000000..d6990c79ff680 --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/PrimaryTypeModel.cs @@ -0,0 +1,225 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java +{ + public class PrimaryTypeModel : PrimaryType, ITypeModel + { + private List _imports; + + public PrimaryTypeModel(KnownPrimaryType knownPrimaryType) + : this (new PrimaryType(knownPrimaryType)) + { + } + + public PrimaryTypeModel(PrimaryType primaryType) + : base (primaryType != null ? primaryType.Type : KnownPrimaryType.None) + { + if (primaryType == null) + { + throw new ArgumentNullException("primaryType"); + } + + this.LoadFrom(primaryType); + _imports = new List(); + Initialize(primaryType); + } + + public string DefaultValue(Method method) + { + if (this.Name == "byte[]") + { + return "new byte[0]"; + } + else if (this.Name == "Byte[]") + { + return "new Byte[0]"; + } + else if (this.Name == "RequestBody") + { + return "RequestBody.create(MediaType.parse(\"" + method.RequestContentType + "\"), new byte[0])"; + } + else if (this.IsInstanceType) + // instance type + { + return "null"; + } + else + { + throw new NotSupportedException(this.Name + " does not have default value!"); + } + } + + public ITypeModel ParameterVariant + { + get + { + if (Type == KnownPrimaryType.DateTimeRfc1123) + { + return new PrimaryTypeModel(KnownPrimaryType.DateTime); + } + else if (Type == KnownPrimaryType.Stream) + { + return new PrimaryTypeModel(KnownPrimaryType.ByteArray); + } + else + { + return this; + } + } + } + + public ITypeModel ResponseVariant + { + get + { + if (Type == KnownPrimaryType.DateTimeRfc1123) + { + return new PrimaryTypeModel(KnownPrimaryType.DateTime); + } + else + { + return this; + } + } + } + + public IEnumerable Imports + { + get + { + return _imports; + } + } + + private bool IsInstanceType + { + get + { + return this.Name[0] >= 'A' && this.Name[0] <= 'Z'; + } + } + + public ITypeModel InstanceType() + { + if (this.IsInstanceType) + { + return this; + } + + PrimaryTypeModel instanceType = new PrimaryTypeModel(this); + if (instanceType.Name == "boolean") + { + instanceType.Name = "Boolean"; + } + else if (instanceType.Name == "double") + { + instanceType.Name = "Double"; + } + else if (instanceType.Name == "int") + { + instanceType.Name = "Integer"; + } + else if (instanceType.Name == "long") + { + instanceType.Name = "Long"; + } + else if (instanceType.Name == "void") + { + instanceType.Name = "Void"; + } + return instanceType; + } + + private void Initialize(PrimaryType primaryType) + { + if (primaryType.Type == KnownPrimaryType.None) + { + Name = "void"; + } + else if (primaryType.Type == KnownPrimaryType.Base64Url) + { + Name = "String"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) + { + Name = "boolean"; + } + else if (primaryType.Type == KnownPrimaryType.ByteArray) + { + Name = "byte[]"; + } + else if (primaryType.Type == KnownPrimaryType.Date) + { + Name = "LocalDate"; + _imports.Add("org.joda.time.LocalDate"); + } + else if (primaryType.Type == KnownPrimaryType.DateTime) + { + Name = "DateTime"; + _imports.Add("org.joda.time.DateTime"); + } + else if (primaryType.Type == KnownPrimaryType.DateTimeRfc1123) + { + Name = "DateTimeRfc1123"; + _imports.Add("com.microsoft.rest.DateTimeRfc1123"); + } + else if (primaryType.Type == KnownPrimaryType.Double) + { + Name = "double"; + } + else if (primaryType.Type == KnownPrimaryType.Decimal) + { + Name = "BigDecimal"; + _imports.Add("java.math.BigDecimal"); + } + else if (primaryType.Type == KnownPrimaryType.Int) + { + Name = "int"; + } + else if (primaryType.Type == KnownPrimaryType.Long) + { + Name = "long"; + } + else if (primaryType.Type == KnownPrimaryType.Stream) + { + Name = "InputStream"; + _imports.Add("java.io.InputStream"); + } + else if (primaryType.Type == KnownPrimaryType.String) + { + Name = "String"; + } + else if (primaryType.Type == KnownPrimaryType.TimeSpan) + { + Name = "Period"; + _imports.Add("org.joda.time.Period"); + } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + Name = "long"; + } + else if (primaryType.Type == KnownPrimaryType.Uuid) + { + Name = "UUID"; + _imports.Add("java.util.UUID"); + } + else if (primaryType.Type == KnownPrimaryType.Object) + { + Name = "Object"; + } + else if (primaryType.Type == KnownPrimaryType.Credentials) + { + Name = "ServiceClientCredentials"; + _imports.Add("com.microsoft.rest.ServiceClientCredentials"); + } + } + } +} diff --git a/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs b/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs new file mode 100644 index 0000000000000..aaed0a6840996 --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/PropertyModel.cs @@ -0,0 +1,41 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java +{ + public class PropertyModel : Property + { + private string _package; + + public PropertyModel(Property property, string package) + : base() + { + this.LoadFrom(property); + this._package = package.ToLower(CultureInfo.InvariantCulture); + } + + public IEnumerable Imports + { + get + { + var imports = new List(Type.ImportSafe() + .Where(c => !c.StartsWith( + string.Join(".", _package, "models"), + StringComparison.OrdinalIgnoreCase))); + if (Type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + imports.AddRange(Type.ImportSafe()); + imports.AddRange(((ITypeModel) Type).ResponseVariant.ImportSafe()); + } + return imports; + } + } + } +} diff --git a/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs new file mode 100644 index 0000000000000..b7a6164ea5bbe --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/ResponseModel.cs @@ -0,0 +1,292 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; +using System.Globalization; + +namespace Microsoft.Rest.Generator.Java +{ + public class ResponseModel + { + protected Response _response; + protected List _interfaceImports; + protected List _implImports; + + public ResponseModel(Response response) + { + this._response = response; + this._interfaceImports = new List(); + this._implImports = new List(); + } + + public ResponseModel(ITypeModel body, ITypeModel headers) + : this(new Response(body, headers)) + { + } + + #region types + + public ITypeModel Body + { + get + { + return (ITypeModel)_response.Body; + } + } + + public ITypeModel Headers + { + get + { + return (ITypeModel)_response.Headers; + } + } + + public bool NeedsConversion + { + get + { + return BodyWireType != BodyClientType || + HeaderWireType != HeaderClientType; + } + } + + public ITypeModel BodyClientType + { + get + { + return BodyWireType.ResponseVariant; + } + } + + private ITypeModel _bodyWireType; + + public ITypeModel BodyWireType + { + get + { + if (_bodyWireType == null) + { + if (Body == null) + { + _bodyWireType = new PrimaryTypeModel(KnownPrimaryType.None) { Name = "void" }; + } + else + { + _bodyWireType = (ITypeModel) Body; + } + } + return _bodyWireType; + } + } + + public ITypeModel HeaderClientType + { + get + { + if (Headers == null) + { + return null; + } + else + { + return HeaderWireType.ResponseVariant; + } + } + } + + public ITypeModel HeaderWireType + { + get + { + if (Headers == null) + { + return null; + } + return (ITypeModel)Headers; + } + } + + public string ConvertBodyToClientType(string source, string target) + { + return convertToClientType(BodyWireType, source, target); + } + + public string ConvertHeaderToClientType(string source, string target) + { + return convertToClientType(HeaderWireType, source, target); + } + + #endregion + + #region template strings + + public string ClientResponseType + { + get + { + if (Headers == null) + { + return "ServiceResponse"; + } + else + { + return "ServiceResponseWithHeaders"; + } + } + } + + public string ClientResponseTypeString + { + get + { + if (Headers == null) + { + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ClientResponseType, GenericBodyClientTypeString); + } + else + { + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ClientResponseType, GenericBodyClientTypeString, GenericHeaderClientTypeString); + } + } + } + + public virtual string ClientCallbackTypeString + { + get + { + return GenericBodyClientTypeString; + } + } + + public string WireResponseTypeString + { + get + { + if (Headers == null) + { + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}>", ClientResponseType, GenericBodyWireTypeString); + } + else + { + return string.Format(CultureInfo.InvariantCulture, "{0}<{1}, {2}>", ClientResponseType, GenericBodyWireTypeString, GenericHeaderWireTypeString); + } + } + } + + public virtual string GenericBodyClientTypeString + { + get + { + return BodyClientType.InstanceType().ResponseVariant.Name; + } + } + + public virtual string GenericHeaderClientTypeString + { + get + { + return HeaderClientType.InstanceType().ResponseVariant.Name; + } + } + + public virtual string GenericBodyWireTypeString + { + get + { + return BodyWireType.InstanceType().Name; + } + } + + public virtual string GenericHeaderWireTypeString + { + get + { + return HeaderWireType.InstanceType().Name; + } + } + + #endregion + + public IEnumerable InterfaceImports + { + get + { + return _interfaceImports.Concat(BodyClientType.ImportSafe()).Concat(HeaderClientType.ImportSafe()); + } + } + + public IEnumerable ImplImports + { + get + { + var imports = new List(InterfaceImports); + imports.AddRange(BodyWireType.ImportSafe()); + imports.AddRange(HeaderWireType.ImportSafe()); + if (this.NeedsConversion && (Body is SequenceType || Headers is SequenceType)) + { + imports.Add("java.util.ArrayList"); + } + if (this.NeedsConversion && (Body is DictionaryType || Headers is DictionaryType)) + { + imports.Add("java.util.HashMap"); + } + return imports; + } + } + + private string convertToClientType(ITypeModel type, string source, string target, int level = 0) + { + if (type == null) + { + return target + " = " + source + ";"; + } + + IndentedStringBuilder builder = new IndentedStringBuilder(); + + SequenceTypeModel sequenceType = type as SequenceTypeModel; + DictionaryTypeModel dictionaryType = type as DictionaryTypeModel; + + if (sequenceType != null) + { + var elementType = sequenceType.ElementTypeModel; + var itemName = string.Format(CultureInfo.InvariantCulture, "item{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + builder.AppendLine("{0} = new ArrayList<{1}>();", target, elementType.ResponseVariant.Name) + .AppendLine("for ({0} {1} : {2}) {{", elementType.Name, itemName, source) + .Indent().AppendLine("{0} {1};", elementType.ResponseVariant.Name, itemTarget) + .AppendLine(convertToClientType(elementType, itemName, itemTarget, level + 1)) + .AppendLine("{0}.add({1});", target, itemTarget) + .Outdent().Append("}"); + _implImports.Add("java.util.ArrayList"); + return builder.ToString(); + } + else if (dictionaryType != null) + { + var valueType = dictionaryType.ValueTypeModel; + var itemName = string.Format(CultureInfo.InvariantCulture, "entry{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + var itemTarget = string.Format(CultureInfo.InvariantCulture, "value{0}", level == 0 ? "" : level.ToString(CultureInfo.InvariantCulture)); + builder.AppendLine("{0} = new HashMap();", target, valueType.ResponseVariant.Name) + .AppendLine("for (Map.Entry {1} : {2}.entrySet()) {{", valueType.Name, itemName, source) + .Indent().AppendLine("{0} {1};", valueType.ResponseVariant.Name, itemTarget) + .AppendLine(convertToClientType(valueType, itemName + ".getValue()", itemTarget, level + 1)) + .AppendLine("{0}.put({1}.getKey(), {2});", target, itemName, itemTarget) + .Outdent().Append("}"); + _implImports.Add("java.util.HashMap"); + return builder.ToString(); + } + else if (type.IsPrimaryType(KnownPrimaryType.DateTimeRfc1123)) + { + return target + " = " + source + ".getDateTime();"; + } + else + { + return target + " = " + source + ";"; + } + } + } +} diff --git a/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs b/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs new file mode 100644 index 0000000000000..447818e312cf6 --- /dev/null +++ b/AutoRest/Generators/Java/Java/TypeModels/SequenceTypeModel.cs @@ -0,0 +1,84 @@ +using Microsoft.Rest.Generator.ClientModel; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; +using Microsoft.Rest.Generator.Java.TemplateModels; +using Microsoft.Rest.Generator.Utilities; + +namespace Microsoft.Rest.Generator.Java +{ + public class SequenceTypeModel : SequenceType, ITypeModel + { + public SequenceTypeModel(SequenceType sequenceType) + : base() + { + this.LoadFrom(sequenceType); + } + + public SequenceTypeModel() + : base() + { + } + + public ITypeModel ElementTypeModel + { + get + { + return (ITypeModel) this.ElementType; + } + } + + public ITypeModel ParameterVariant + { + get + { + if (ElementTypeModel.ParameterVariant != ElementTypeModel) + { + return new SequenceTypeModel(new SequenceType() + { + NameFormat = "List<{0}>", + ElementType = ElementTypeModel.ParameterVariant + }); + } + return this; + } + } + + public ITypeModel ResponseVariant + { + get + { + if (ElementTypeModel.ResponseVariant != ElementTypeModel) + { + return new SequenceTypeModel(new SequenceType() + { + NameFormat = "List<{0}>", + ElementType = ElementTypeModel.ResponseVariant + }); + } + return this; + } + } + + public string DefaultValue(Method method) + { + return "null"; + } + + public IEnumerable Imports + { + get + { + List imports = new List { "java.util.List" }; + return imports.Concat(((ITypeModel) this.ElementType).Imports); + } + } + + public ITypeModel InstanceType() + { + return this; + } + } +} diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/AcceptanceTests/azureCustomBaseUri.js b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/AcceptanceTests/azureCustomBaseUri.js index 70960a0e0895e..c50f1f521a66d 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/AcceptanceTests/azureCustomBaseUri.js +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/AcceptanceTests/azureCustomBaseUri.js @@ -18,7 +18,8 @@ var clientOptions = {}; describe('nodejs', function () { describe('Custom BaseUri Client', function () { - var testClient = new customBaseUriClient(credentials, 'host:3000', clientOptions); + clientOptions.host = 'host:3000'; + var testClient = new customBaseUriClient(credentials, clientOptions); it('should return 200', function (done) { testClient.paths.getEmpty('local', function (error, result, request, response) { should.not.exist(error); diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/models/durationWrapper.js b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/models/durationWrapper.js index 3eba03688006e..05c4a93c4a750 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/models/durationWrapper.js +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/AzureCompositeModelClient/models/durationWrapper.js @@ -10,8 +10,6 @@ 'use strict'; -var moment = require('moment'); - /** * @class * Initializes a new instance of the DurationWrapper class. diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts index 59cea5a89b930..5092268e0db7c 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts @@ -19,8 +19,6 @@ declare class AutoRestParameterizedHostTestClient { * * @param {credentials} credentials - Gets Azure subscription credentials. * - * @param {string} host - A string value that is used as a global part of the parameterized host - * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline @@ -30,6 +28,8 @@ declare class AutoRestParameterizedHostTestClient { * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * + * @param {string} [options.host] - A string value that is used as a global part of the parameterized host + * * @param {string} [options.acceptLanguage] - Gets or sets the preferred language for the response. * * @param {number} [options.longRunningOperationRetryTimeout] - Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. @@ -37,7 +37,7 @@ declare class AutoRestParameterizedHostTestClient { * @param {boolean} [options.generateClientRequestId] - When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * */ - constructor(credentials: ServiceClientCredentials, host: string, options: ServiceClientOptions); + constructor(credentials: ServiceClientCredentials, options: ServiceClientOptions); credentials: ServiceClientCredentials; diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js index 9c7f803b703ef..43f7a3c828168 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js @@ -29,8 +29,6 @@ var operations = require('./operations'); * * @param {credentials} credentials - Gets Azure subscription credentials. * - * @param {string} host - A string value that is used as a global part of the parameterized host - * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline @@ -40,6 +38,8 @@ var operations = require('./operations'); * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * + * @param {string} [options.host] - A string value that is used as a global part of the parameterized host + * * @param {string} [options.acceptLanguage] - Gets or sets the preferred language for the response. * * @param {number} [options.longRunningOperationRetryTimeout] - Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. @@ -47,7 +47,7 @@ var operations = require('./operations'); * @param {boolean} [options.generateClientRequestId] - When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * */ -function AutoRestParameterizedHostTestClient(credentials, host, options) { +function AutoRestParameterizedHostTestClient(credentials, options) { this.host = 'host'; this.acceptLanguage = 'en-US'; this.longRunningOperationRetryTimeout = 30; @@ -55,19 +55,16 @@ function AutoRestParameterizedHostTestClient(credentials, host, options) { if (credentials === null || credentials === undefined) { throw new Error('\'credentials\' cannot be null.'); } - if (host === null || host === undefined) { - throw new Error('\'host\' cannot be null.'); - } if (!options) options = {}; AutoRestParameterizedHostTestClient['super_'].call(this, credentials, options); - if (!this.baseUri) { - this.baseUri = 'http://{accountName}{host}'; - } + this.baseUri = 'http://{accountName}{host}'; this.credentials = credentials; - this.host = host; + if(options.host !== null && options.host !== undefined) { + this.host = options.host; + } if(options.acceptLanguage !== null && options.acceptLanguage !== undefined) { this.acceptLanguage = options.acceptLanguage; } diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs b/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs index cddd7a2adba46..ac8eea6fb028a 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs @@ -18,7 +18,7 @@ namespace Microsoft.Rest.Generator.Azure.NodeJS { public class AzureNodeJSCodeGenerator : NodeJSCodeGenerator { - private const string ClientRuntimePackage = "ms-rest-azure version 1.10.0"; + private const string ClientRuntimePackage = "ms-rest-azure version 1.12.0"; // List of models with paging extensions. private IList pageModels; diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplate.cshtml b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplate.cshtml index cdfc5a425ea54..e0639dec63e0b 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplate.cshtml +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplate.cshtml @@ -40,8 +40,8 @@ var ServiceClient = msRestAzure.AzureServiceClient; @:var operations = require('./operations'); } @EmptyLine -@{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant);} -@{var optionalParameters = Model.Properties.Where(p => !p.IsRequired && !p.IsConstant);} +@{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue));} +@{var optionalParameters = Model.Properties.Where(p => (!p.IsRequired || p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue)) && !p.IsConstant);} /** * @@class * Initializes a new instance of the @Model.Name class. @@ -73,7 +73,7 @@ var ServiceClient = msRestAzure.AzureServiceClient; @: * } */ -function @(Model.Name)(@(Model.RequiredConstructorParameters), options) { +function @(Model.Name)(@(!string.IsNullOrEmpty(Model.RequiredConstructorParameters) ? Model.RequiredConstructorParameters + ", " : "")options) { @foreach (var property in Model.Properties.Where(p => p.DefaultValue != null)) { @:this.@(property.Name) = @(property.DefaultValue); @@ -91,11 +91,16 @@ function @(Model.Name)(@(Model.RequiredConstructorParameters), options) { @if(!Model.IsCustomBaseUri) { @:this.baseUri = baseUri; + @:if (!this.baseUri) { + @:this.baseUri = '@Model.BaseUrl'; + @:} +} +else +{ + @:this.baseUri = '@Model.BaseUrl'; } - if (!this.baseUri) { - this.baseUri = '@Model.BaseUrl'; - } + @foreach (var param in requiredParameters) { @: this.@(param.Name) = @(param.Name); diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplateTS.cshtml b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplateTS.cshtml index b7142e35c49e4..5448c378c401c 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplateTS.cshtml +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/AzureServiceClientTemplateTS.cshtml @@ -18,8 +18,8 @@ import { ServiceClientOptions, RequestOptions, ServiceCallback, ServiceClientCre } @EmptyLine declare class @(Model.Name) { - @{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant);} - @{var optionalParameters = Model.Properties.Where(p => !p.IsRequired && !p.IsConstant);} + @{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue));} + @{var optionalParameters = Model.Properties.Where(p => (!p.IsRequired || p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue)) && !p.IsConstant);} /** * @@class * Initializes a new instance of the @Model.Name class. @@ -52,7 +52,7 @@ declare class @(Model.Name) { @: * } */ - constructor(@(Model.RequiredConstructorParametersTS), options: ServiceClientOptions); + constructor(@(!string.IsNullOrEmpty(Model.RequiredConstructorParametersTS) ? Model.RequiredConstructorParametersTS + ", " : "")options: ServiceClientOptions); @foreach (var property in Model.Properties) { diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/PageModelTemplate.cshtml b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/PageModelTemplate.cshtml index 4f714041a98a5..36056f6225333 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/PageModelTemplate.cshtml +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS/Templates/PageModelTemplate.cshtml @@ -14,11 +14,6 @@ @EmptyLine var util = require('util'); @EmptyLine -@if (Model.ContainsDurationProperty()) -{ -@:var moment = require('moment'); -@EmptyLine -} /** * @@class * Initializes a new instance of the @(Model.Name) class. diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts index 66a8cbc2da740..0a81b3420068b 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts @@ -32,7 +32,7 @@ import dictionaryModels = require('../Expected/AcceptanceTests/BodyDictionary/mo import httpClient = require('../Expected/AcceptanceTests/Http/autoRestHttpInfrastructureTestService'); import formDataClient = require('../Expected/AcceptanceTests/BodyFormData/autoRestSwaggerBATFormDataService'); import customBaseUriClient = require('../Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient'); - +import customBaseUriClientMoreOptions = require('../Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient'); var dummyToken = 'dummy12321343423'; var credentials = new msRest.TokenCredentials(dummyToken); @@ -65,7 +65,10 @@ describe('nodejs', function () { describe('Swagger BAT', function () { describe('Custom BaseUri Client', function () { - var testClient = new customBaseUriClient('host:3000', clientOptions); + var customOptions = { + host: 'host:3000' + }; + var testClient = new customBaseUriClient(customOptions); it('should return 200', function (done) { testClient.paths.getEmpty('local', function (error, result, request, response) { should.not.exist(error); @@ -91,6 +94,19 @@ describe('nodejs', function () { }); }); }); + describe('Custom BaseUri Client with more options', function () { + var customOptions = { + dnsSuffix: 'host:3000' + }; + var testClient = new customBaseUriClientMoreOptions('test12', customOptions); + it('should return 200', function (done) { + testClient.paths.getEmpty('http://lo','cal', 'key1', function (error, result, request, response) { + should.not.exist(error); + response.statusCode.should.equal(200); + done(); + }); + }); + }); describe('Bool Client', function () { var testClient = new boolClient(baseUri, clientOptions); it('should get valid boolean values', function (done) { @@ -428,6 +444,37 @@ describe('nodejs', function () { done(); }); }); + + it('should correctly deserialize base64 encoded string', function (done) { + testClient.string.getBase64Encoded(function (error, result) { + should.not.exist(error); + should.exist(result); + result.toString('utf8').should.equal('a string that gets encoded with base64'); + done(); + }); + }); + + it('should correctly handle null base64url encoded string', function (done) { + testClient.string.getNullBase64UrlEncoded(function (error, result) { + should.not.exist(error); + should.not.exist(result); + done(); + }); + }); + + it('should correctly serialize and deserialize base64url encoded string', function (done) { + testClient.string.getBase64UrlEncoded(function (error, result) { + should.not.exist(error); + should.exist(result); + result.toString('utf8').should.equal('a string that gets encoded with base64url'); + var buff = new Buffer('a string that gets encoded with base64url', 'utf8'); + testClient.string.putBase64UrlEncoded(buff, function (error, result) { + should.not.exist(error); + should.not.exist(result); + done(); + }); + }); + }); }); describe('Byte Client', function () { @@ -911,6 +958,19 @@ describe('nodejs', function () { }); }); + it('should get base64url arrays', function (done) { + var base64Url1 = new Buffer('a string that gets encoded with base64url', 'utf8'); + var base64Url2 = new Buffer('test string', 'utf8'); + var base64Url3 = new Buffer('Lorem ipsum', 'utf8'); + var arr = [base64Url1, base64Url2, base64Url3]; + testClient.arrayModel.getBase64Url(function (error, result) { + should.not.exist(error); + should.exist(result); + assert.deepEqual(result, arr); + done(); + }); + }); + it('should get and put boolean arrays', function (done) { var boolArray = [true, false, false, true]; testClient.arrayModel.getBooleanTfft(function (error, result) { @@ -1293,6 +1353,18 @@ describe('nodejs', function () { }); }); + it('should get base64url dictionaries', function (done) { + var base64Url1 = new Buffer('a string that gets encoded with base64url', 'utf8'); + var base64Url2 = new Buffer('test string', 'utf8'); + var base64Url3 = new Buffer('Lorem ipsum', 'utf8'); + var dict: { [propertyName: string]: Buffer } = { "0": base64Url1, "1": base64Url2, "2": base64Url3 }; + testClient.dictionary.getBase64Url(function (error, result) { + should.not.exist(error); + assert.deepEqual(result, dict); + done(); + }); + }); + it('should get and put boolean dictionaries', function (done) { var boolDictionary: { [propertyName: string]: boolean } = { "0": true, "1": false, "2": false, "3": true }; testClient.dictionary.getBooleanTfft(function (error, result) { @@ -1797,6 +1869,7 @@ describe('nodejs', function () { }); }); }); + it('should work when path has string', function (done) { testClient.paths.stringEmpty('', function (error, result) { should.not.exist(error); @@ -1810,6 +1883,14 @@ describe('nodejs', function () { }); }); + it('should work when path has base64url encoded string', function (done) { + testClient.paths.base64Url(new Buffer('lorem', 'utf8'), function (error, result) { + should.not.exist(error); + should.not.exist(result); + done(); + }); + }); + it('should work when path has datetime', function (done) { testClient.paths.dateTimeValid(new Date('2012-01-01T01:01:01Z'), function (error, result) { should.not.exist(error); @@ -2022,6 +2103,13 @@ describe('nodejs', function () { }); }); }); + it('should work when path has string array values', function (done) { + var testArray = ['ArrayPath1', 'begin!*\'();:@ &=+$,/?#[]end', null, '']; + testClient.paths.arrayCsvInPath(testArray, function (error, result) { + should.not.exist(error); + done(); + }); + }); it('should work when use null values in url query', function (done) { testClient.queries.byteNull({ byteQuery: null }, function (error, result) { should.not.exist(error); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/modelFlattening.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/modelFlattening.ts index d0d27d37d3324..46d5db6758604 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/modelFlattening.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/modelFlattening.ts @@ -188,7 +188,8 @@ describe('nodejs', function () { productId: "123", description: "product description", maxProductDisplayName: "max name", - odatavalue: "http://foo" + odatavalue: "http://foo", + genericValue: "https://generic" }; testClient.putSimpleProduct({ simpleBodyProduct: resourceBody }, function (error, result) { should.not.exist(error); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/arrayModel.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/arrayModel.js index bd4bb202801cd..3718eebb86cc3 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/arrayModel.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/arrayModel.js @@ -5765,6 +5765,128 @@ ArrayModel.prototype.getByteInvalidNull = function (options, callback) { }); }; +/** + * Get array value ['a string that gets encoded with base64url', 'test string' + * 'Lorem ipsum'] with the items base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {array} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +ArrayModel.prototype.getBase64Url = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//array/prim/base64url/valid'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Sequence', + element: { + required: false, + serializedName: 'BufferElementType', + type: { + name: 'Base64Url' + } + } + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + /** * Get array of complex type null value * diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/index.d.ts index 76f9a3ab41aee..b09e78940d731 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyArray/operations/index.d.ts @@ -702,6 +702,21 @@ export interface ArrayModel { getByteInvalidNull(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; getByteInvalidNull(callback: ServiceCallback): void; + /** + * Get array value ['a string that gets encoded with base64url', 'test string' + * 'Lorem ipsum'] with the items base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getBase64Url(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getBase64Url(callback: ServiceCallback): void; + /** * Get array of complex type null value * diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/models/durationWrapper.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/models/durationWrapper.js index 3eba03688006e..05c4a93c4a750 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/models/durationWrapper.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyComplex/models/durationWrapper.js @@ -10,8 +10,6 @@ 'use strict'; -var moment = require('moment'); - /** * @class * Initializes a new instance of the DurationWrapper class. diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/dictionary.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/dictionary.js index cc8188335cd97..0ca951fc9f28c 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/dictionary.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/dictionary.js @@ -5753,6 +5753,128 @@ Dictionary.prototype.getByteInvalidNull = function (options, callback) { }); }; +/** + * Get base64url dictionary value {"0": "a string that gets encoded with + * base64url", "1": "test string", "2": "Lorem ipsum"} + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {object} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +Dictionary.prototype.getBase64Url = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//dictionary/prim/base64url/valid'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Dictionary', + value: { + required: false, + serializedName: 'BufferElementType', + type: { + name: 'Base64Url' + } + } + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + /** * Get dictionary of complex type null value * diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/index.d.ts index 22de054220cd9..45d1abe7996dc 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyDictionary/operations/index.d.ts @@ -700,6 +700,21 @@ export interface Dictionary { getByteInvalidNull(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<{ [propertyName: string]: Buffer }>): void; getByteInvalidNull(callback: ServiceCallback<{ [propertyName: string]: Buffer }>): void; + /** + * Get base64url dictionary value {"0": "a string that gets encoded with + * base64url", "1": "test string", "2": "Lorem ipsum"} + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getBase64Url(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<{ [propertyName: string]: Buffer }>): void; + getBase64Url(callback: ServiceCallback<{ [propertyName: string]: Buffer }>): void; + /** * Get dictionary of complex type null value * diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/index.d.ts index 387cdc5e61570..1d5e9935b6520 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/index.d.ts @@ -161,6 +161,64 @@ export interface String { */ getNotProvided(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; getNotProvided(callback: ServiceCallback): void; + + /** + * Get value that is base64 encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getBase64Encoded(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getBase64Encoded(callback: ServiceCallback): void; + + /** + * Get value that is base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getBase64UrlEncoded(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getBase64UrlEncoded(callback: ServiceCallback): void; + + /** + * Put value that is base64url encoded + * + * @param {buffer} stringBody + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + putBase64UrlEncoded(stringBody: Buffer, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + putBase64UrlEncoded(stringBody: Buffer, callback: ServiceCallback): void; + + /** + * Get null value that is expected to be base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getNullBase64UrlEncoded(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getNullBase64UrlEncoded(callback: ServiceCallback): void; } /** diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/string.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/string.js index a17875013063e..eb0c1554c2764 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/string.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyString/operations/string.js @@ -1091,5 +1091,468 @@ String.prototype.getNotProvided = function (options, callback) { }); }; +/** + * Get value that is base64 encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {buffer} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +String.prototype.getBase64Encoded = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//string/base64Encoding'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Base64Url' + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + +/** + * Get value that is base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {buffer} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +String.prototype.getBase64UrlEncoded = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//string/base64UrlEncoding'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Base64Url' + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + +/** + * Put value that is base64url encoded + * + * @param {buffer} stringBody + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {null} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +String.prototype.putBase64UrlEncoded = function (stringBody, options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + // Validate + try { + if (!Buffer.isBuffer(stringBody)) { + throw new Error('stringBody cannot be null or undefined and it must be of type buffer.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//string/base64UrlEncoding'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'PUT'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + // Serialize Request + var requestContent = null; + var requestModel = null; + try { + if (stringBody !== null && stringBody !== undefined) { + var requestModelMapper = { + required: true, + serializedName: 'stringBody', + type: { + name: 'Base64Url' + } + }; + requestModel = client.serialize(requestModelMapper, stringBody, 'stringBody'); + requestContent = JSON.stringify(requestModel); + } + } catch (error) { + var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + + 'payload - "%s"', error.message, util.inspect(stringBody, {depth: null}))); + return callback(serializationError); + } + httpRequest.body = requestContent; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + + return callback(null, result, httpRequest, response); + }); +}; + +/** + * Get null value that is expected to be base64url encoded + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {buffer} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +String.prototype.getNullBase64UrlEncoded = function (options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//string/nullBase64UrlEncoding'; + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + // Deserialize Response + if (statusCode === 200) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = { + required: false, + serializedName: 'parsedResponse', + type: { + name: 'Base64Url' + } + }; + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError.request = msRest.stripRequest(httpRequest); + deserializationError.response = msRest.stripResponse(response); + return callback(deserializationError); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + module.exports = String; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts index 7dfd384801704..55373a0e9682c 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.d.ts @@ -17,8 +17,6 @@ declare class AutoRestParameterizedHostTestClient { * Initializes a new instance of the AutoRestParameterizedHostTestClient class. * @constructor * - * @param {string} host - A string value that is used as a global part of the parameterized host - * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline @@ -28,8 +26,10 @@ declare class AutoRestParameterizedHostTestClient { * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * + * @param {string} [options.host] - A string value that is used as a global part of the parameterized host + * */ - constructor(host: string, options: ServiceClientOptions); + constructor(options: ServiceClientOptions); host: string; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js index 96817a9819895..84e01146a9845 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUri/autoRestParameterizedHostTestClient.js @@ -26,8 +26,6 @@ var operations = require('./operations'); * Initializes a new instance of the AutoRestParameterizedHostTestClient class. * @constructor * - * @param {string} host - A string value that is used as a global part of the parameterized host - * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline @@ -37,21 +35,20 @@ var operations = require('./operations'); * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * + * @param {string} [options.host] - A string value that is used as a global part of the parameterized host + * */ -function AutoRestParameterizedHostTestClient(host, options) { +function AutoRestParameterizedHostTestClient(options) { this.host = 'host'; - if (host === null || host === undefined) { - throw new Error('\'host\' cannot be null.'); - } if (!options) options = {}; AutoRestParameterizedHostTestClient['super_'].call(this, null, options); - if (!this.baseUri) { - this.baseUri = 'http://{accountName}{host}'; - } - this.host = host; + this.baseUri = 'http://{accountName}{host}'; + if(options.host !== null && options.host !== undefined) { + this.host = options.host; + } this.paths = new operations.Paths(this); this.models = models; msRest.addSerializationMixin(this); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.d.ts new file mode 100644 index 0000000000000..98c22ab85f4de --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.d.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +import { ServiceClientOptions, RequestOptions, ServiceCallback } from 'ms-rest'; +import * as operations from "./operations"; + +declare class AutoRestParameterizedCustomHostTestClient { + /** + * @class + * Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + * @constructor + * + * @param {string} subscriptionId - The subscription id with value 'test12'. + * + * @param {object} [options] - The parameter options + * + * @param {Array} [options.filters] - Filters to be added to the request pipeline + * + * @param {object} [options.requestOptions] - Options for the underlying request object + * {@link https://github.com/request/request#requestoptions-callback Options doc} + * + * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy + * + * @param {string} [options.dnsSuffix] - A string value that is used as a global part of the parameterized host. Default value 'host'. + * + */ + constructor(subscriptionId: string, options: ServiceClientOptions); + + subscriptionId: string; + + dnsSuffix: string; + + // Operation groups + paths: operations.Paths; + } + +export = AutoRestParameterizedCustomHostTestClient; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.js new file mode 100644 index 0000000000000..391f7b50deb38 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.js @@ -0,0 +1,65 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +/* jshint latedef:false */ +/* jshint forin:false */ +/* jshint noempty:false */ + +'use strict'; + +var util = require('util'); +var msRest = require('ms-rest'); +var ServiceClient = msRest.ServiceClient; + +var models = require('./models'); +var operations = require('./operations'); + +/** + * @class + * Initializes a new instance of the AutoRestParameterizedCustomHostTestClient class. + * @constructor + * + * @param {string} subscriptionId - The subscription id with value 'test12'. + * + * @param {object} [options] - The parameter options + * + * @param {Array} [options.filters] - Filters to be added to the request pipeline + * + * @param {object} [options.requestOptions] - Options for the underlying request object + * {@link https://github.com/request/request#requestoptions-callback Options doc} + * + * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy + * + * @param {string} [options.dnsSuffix] - A string value that is used as a global part of the parameterized host. Default value 'host'. + * + */ +function AutoRestParameterizedCustomHostTestClient(subscriptionId, options) { + this.dnsSuffix = 'host'; + if (subscriptionId === null || subscriptionId === undefined) { + throw new Error('\'subscriptionId\' cannot be null.'); + } + + if (!options) options = {}; + + AutoRestParameterizedCustomHostTestClient['super_'].call(this, null, options); + this.baseUri = '{vault}{secret}{dnsSuffix}'; + this.subscriptionId = subscriptionId; + + if(options.dnsSuffix !== null && options.dnsSuffix !== undefined) { + this.dnsSuffix = options.dnsSuffix; + } + this.paths = new operations.Paths(this); + this.models = models; + msRest.addSerializationMixin(this); +} + +util.inherits(AutoRestParameterizedCustomHostTestClient, ServiceClient); + +module.exports = AutoRestParameterizedCustomHostTestClient; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/errorModel.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/errorModel.js new file mode 100644 index 0000000000000..663be0f4aaa8c --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/errorModel.js @@ -0,0 +1,58 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +'use strict'; + +/** + * @class + * Initializes a new instance of the ErrorModel class. + * @constructor + * @member {number} [status] + * + * @member {string} [message] + * + */ +function ErrorModel() { +} + +/** + * Defines the metadata of ErrorModel + * + * @returns {object} metadata of ErrorModel + * + */ +ErrorModel.prototype.mapper = function () { + return { + required: false, + serializedName: 'Error', + type: { + name: 'Composite', + className: 'ErrorModel', + modelProperties: { + status: { + required: false, + serializedName: 'status', + type: { + name: 'Number' + } + }, + message: { + required: false, + serializedName: 'message', + type: { + name: 'String' + } + } + } + } + }; +}; + +module.exports = ErrorModel; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.d.ts new file mode 100644 index 0000000000000..5405a199a0755 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.d.ts @@ -0,0 +1,24 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + + +/** + * @class + * Initializes a new instance of the ErrorModel class. + * @constructor + * @member {number} [status] + * + * @member {string} [message] + * + */ +export interface ErrorModel { + status?: number; + message?: string; +} diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.js new file mode 100644 index 0000000000000..3430295d8bd86 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.js @@ -0,0 +1,17 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +/* jshint latedef:false */ +/* jshint forin:false */ +/* jshint noempty:false */ + +'use strict'; + +exports.ErrorModel = require('./errorModel'); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.d.ts new file mode 100644 index 0000000000000..3fa4ea5d9bf14 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.d.ts @@ -0,0 +1,44 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. +*/ + +import { ServiceClientOptions, RequestOptions, ServiceCallback } from 'ms-rest'; +import * as models from '../models'; + + +/** + * @class + * Paths + * __NOTE__: An instance of this class is automatically created for an + * instance of the AutoRestParameterizedCustomHostTestClient. + */ +export interface Paths { + + /** + * Get a 200 to test a valid base uri + * + * @param {string} vault The vault name, e.g. https://myvault + * + * @param {string} secret Secret value. + * + * @param {string} keyName The key name with value 'key1'. + * + * @param {object} [options] Optional Parameters. + * + * @param {string} [options.keyVersion] The key version. Default value 'v1'. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + getEmpty(vault: string, secret: string, keyName: string, options: { keyVersion? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getEmpty(vault: string, secret: string, keyName: string, callback: ServiceCallback): void; +} diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.js new file mode 100644 index 0000000000000..412d88e67668a --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.js @@ -0,0 +1,17 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +/* jshint latedef:false */ +/* jshint forin:false */ +/* jshint noempty:false */ + +'use strict'; + +exports.Paths = require('./paths'); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/paths.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/paths.js new file mode 100644 index 0000000000000..dc2c66f05c60e --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/paths.js @@ -0,0 +1,167 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +'use strict'; + +var util = require('util'); +var msRest = require('ms-rest'); +var WebResource = msRest.WebResource; + +/** + * @class + * Paths + * __NOTE__: An instance of this class is automatically created for an + * instance of the AutoRestParameterizedCustomHostTestClient. + * Initializes a new instance of the Paths class. + * @constructor + * + * @param {AutoRestParameterizedCustomHostTestClient} client Reference to the service client. + */ +function Paths(client) { + this.client = client; +} + +/** + * Get a 200 to test a valid base uri + * + * @param {string} vault The vault name, e.g. https://myvault + * + * @param {string} secret Secret value. + * + * @param {string} keyName The key name with value 'key1'. + * + * @param {object} [options] Optional Parameters. + * + * @param {string} [options.keyVersion] The key version. Default value 'v1'. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {null} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +Paths.prototype.getEmpty = function (vault, secret, keyName, options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + var keyVersion = (options && options.keyVersion !== undefined) ? options.keyVersion : 'v1'; + // Validate + try { + if (vault === null || vault === undefined || typeof vault.valueOf() !== 'string') { + throw new Error('vault cannot be null or undefined and it must be of type string.'); + } + if (secret === null || secret === undefined || typeof secret.valueOf() !== 'string') { + throw new Error('secret cannot be null or undefined and it must be of type string.'); + } + if (this.client.dnsSuffix === null || this.client.dnsSuffix === undefined || typeof this.client.dnsSuffix.valueOf() !== 'string') { + throw new Error('this.client.dnsSuffix cannot be null or undefined and it must be of type string.'); + } + if (keyName === null || keyName === undefined || typeof keyName.valueOf() !== 'string') { + throw new Error('keyName cannot be null or undefined and it must be of type string.'); + } + if (this.client.subscriptionId === null || this.client.subscriptionId === undefined || typeof this.client.subscriptionId.valueOf() !== 'string') { + throw new Error('this.client.subscriptionId cannot be null or undefined and it must be of type string.'); + } + if (keyVersion !== null && keyVersion !== undefined && typeof keyVersion.valueOf() !== 'string') { + throw new Error('keyVersion must be of type string.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//customuri/{subscriptionId}/{keyName}'; + requestUrl = requestUrl.replace('{vault}', vault); + requestUrl = requestUrl.replace('{secret}', secret); + requestUrl = requestUrl.replace('{dnsSuffix}', this.client.dnsSuffix); + requestUrl = requestUrl.replace('{keyName}', encodeURIComponent(keyName)); + requestUrl = requestUrl.replace('{subscriptionId}', encodeURIComponent(this.client.subscriptionId)); + var queryParameters = []; + if (keyVersion !== null && keyVersion !== undefined) { + queryParameters.push('keyVersion=' + encodeURIComponent(keyVersion)); + } + if (queryParameters.length > 0) { + requestUrl += '?' + queryParameters.join('&'); + } + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + + return callback(null, result, httpRequest, response); + }); +}; + + +module.exports = Paths; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.d.ts index 5fddcc86f30e4..1435eb6ff6c54 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.d.ts @@ -152,6 +152,8 @@ declare class AutoRestResourceFlatteningTestService { * @param {string} [options.simpleBodyProduct.maxProductDisplayName] Display * name of product. * + * @param {string} [options.simpleBodyProduct.genericValue] Generic URL value. + * * @param {string} [options.simpleBodyProduct.odatavalue] URL value. * * @param {string} [options.simpleBodyProduct.productId] Unique identifier @@ -184,6 +186,8 @@ declare class AutoRestResourceFlatteningTestService { * * @param {string} [options.description] Description of product. * + * @param {string} [options.genericValue] Generic URL value. + * * @param {string} [options.odatavalue] URL value. * * @param {object} [options.customHeaders] Headers that will be added to the @@ -192,7 +196,7 @@ declare class AutoRestResourceFlatteningTestService { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - postFlattenedSimpleProduct(productId: string, maxProductDisplayName: string, options: { description? : string, odatavalue? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + postFlattenedSimpleProduct(productId: string, maxProductDisplayName: string, options: { description? : string, genericValue? : string, odatavalue? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; postFlattenedSimpleProduct(productId: string, maxProductDisplayName: string, callback: ServiceCallback): void; /** @@ -214,6 +218,8 @@ declare class AutoRestResourceFlatteningTestService { * @param {string} [flattenParameterGroup.maxProductDisplayName] Display name * of product. * + * @param {string} [flattenParameterGroup.genericValue] Generic URL value. + * * @param {string} [flattenParameterGroup.odatavalue] URL value. * * @param {object} [options] Optional Parameters. diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.js index 447c63d2fe467..b8f3616ea6bc8 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/autoRestResourceFlatteningTestService.js @@ -790,6 +790,8 @@ AutoRestResourceFlatteningTestService.prototype.getResourceCollection = function * @param {string} [options.simpleBodyProduct.maxProductDisplayName] Display * name of product. * + * @param {string} [options.simpleBodyProduct.genericValue] Generic URL value. + * * @param {string} [options.simpleBodyProduct.odatavalue] URL value. * * @param {string} [options.simpleBodyProduct.productId] Unique identifier @@ -932,6 +934,8 @@ AutoRestResourceFlatteningTestService.prototype.putSimpleProduct = function (opt * * @param {string} [options.description] Description of product. * + * @param {string} [options.genericValue] Generic URL value. + * * @param {string} [options.odatavalue] URL value. * * @param {object} [options.customHeaders] Headers that will be added to the @@ -960,6 +964,7 @@ AutoRestResourceFlatteningTestService.prototype.postFlattenedSimpleProduct = fun throw new Error('callback cannot be null.'); } var description = (options && options.description !== undefined) ? options.description : undefined; + var genericValue = (options && options.genericValue !== undefined) ? options.genericValue : undefined; var odatavalue = (options && options.odatavalue !== undefined) ? options.odatavalue : undefined; // Validate try { @@ -972,6 +977,9 @@ AutoRestResourceFlatteningTestService.prototype.postFlattenedSimpleProduct = fun if (maxProductDisplayName === null || maxProductDisplayName === undefined || typeof maxProductDisplayName.valueOf() !== 'string') { throw new Error('maxProductDisplayName cannot be null or undefined and it must be of type string.'); } + if (genericValue !== null && genericValue !== undefined && typeof genericValue.valueOf() !== 'string') { + throw new Error('genericValue must be of type string.'); + } if (odatavalue !== null && odatavalue !== undefined && typeof odatavalue.valueOf() !== 'string') { throw new Error('odatavalue must be of type string.'); } @@ -980,12 +988,13 @@ AutoRestResourceFlatteningTestService.prototype.postFlattenedSimpleProduct = fun } var simpleBodyProduct; try { - if ((productId !== null && productId !== undefined) || (description !== null && description !== undefined) || (maxProductDisplayName !== null && maxProductDisplayName !== undefined) || (odatavalue !== null && odatavalue !== undefined)) + if ((productId !== null && productId !== undefined) || (description !== null && description !== undefined) || (maxProductDisplayName !== null && maxProductDisplayName !== undefined) || (genericValue !== null && genericValue !== undefined) || (odatavalue !== null && odatavalue !== undefined)) { simpleBodyProduct = new client.models['SimpleProduct'](); simpleBodyProduct.productId = productId; simpleBodyProduct.description = description; simpleBodyProduct.maxProductDisplayName = maxProductDisplayName; + simpleBodyProduct.genericValue = genericValue; simpleBodyProduct.odatavalue = odatavalue; } } catch (error) { @@ -1103,6 +1112,8 @@ AutoRestResourceFlatteningTestService.prototype.postFlattenedSimpleProduct = fun * @param {string} [flattenParameterGroup.maxProductDisplayName] Display name * of product. * + * @param {string} [flattenParameterGroup.genericValue] Generic URL value. + * * @param {string} [flattenParameterGroup.odatavalue] URL value. * * @param {object} [options] Optional Parameters. @@ -1144,6 +1155,7 @@ AutoRestResourceFlatteningTestService.prototype.putSimpleProductWithGrouping = f var productId; var description; var maxProductDisplayName; + var genericValue; var odatavalue; var simpleBodyProduct; try { @@ -1176,18 +1188,26 @@ AutoRestResourceFlatteningTestService.prototype.putSimpleProductWithGrouping = f } } if (flattenParameterGroup !== null && flattenParameterGroup !== undefined) + { + genericValue = flattenParameterGroup.genericValue; + if (genericValue !== null && genericValue !== undefined && typeof genericValue.valueOf() !== 'string') { + throw new Error('genericValue must be of type string.'); + } + } + if (flattenParameterGroup !== null && flattenParameterGroup !== undefined) { odatavalue = flattenParameterGroup.odatavalue; if (odatavalue !== null && odatavalue !== undefined && typeof odatavalue.valueOf() !== 'string') { throw new Error('odatavalue must be of type string.'); } } - if ((productId !== null && productId !== undefined) || (description !== null && description !== undefined) || (maxProductDisplayName !== null && maxProductDisplayName !== undefined) || (odatavalue !== null && odatavalue !== undefined)) + if ((productId !== null && productId !== undefined) || (description !== null && description !== undefined) || (maxProductDisplayName !== null && maxProductDisplayName !== undefined) || (genericValue !== null && genericValue !== undefined) || (odatavalue !== null && odatavalue !== undefined)) { simpleBodyProduct = new client.models['SimpleProduct'](); simpleBodyProduct.productId = productId; simpleBodyProduct.description = description; simpleBodyProduct.maxProductDisplayName = maxProductDisplayName; + simpleBodyProduct.genericValue = genericValue; simpleBodyProduct.odatavalue = odatavalue; } } catch (error) { diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/flattenParameterGroup.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/flattenParameterGroup.js index 212317768692f..d548e2c6afea8 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/flattenParameterGroup.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/flattenParameterGroup.js @@ -25,6 +25,8 @@ * * @member {string} maxProductDisplayName Display name of product. * + * @member {string} [genericValue] Generic URL value. + * * @member {string} [odatavalue] URL value. * */ @@ -68,6 +70,12 @@ FlattenParameterGroup.prototype.mapper = function () { name: 'String' } }, + genericValue: { + required: false, + type: { + name: 'String' + } + }, odatavalue: { required: false, type: { diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/genericUrl.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/genericUrl.js new file mode 100644 index 0000000000000..cd657aa822f64 --- /dev/null +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/genericUrl.js @@ -0,0 +1,50 @@ +/* + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * Changes may cause incorrect behavior and will be lost if the code is + * regenerated. + */ + +'use strict'; + +/** + * @class + * Initializes a new instance of the GenericUrl class. + * @constructor + * The Generic URL. + * @member {string} [genericValue] Generic URL value. + * + */ +function GenericUrl() { +} + +/** + * Defines the metadata of GenericUrl + * + * @returns {object} metadata of GenericUrl + * + */ +GenericUrl.prototype.mapper = function () { + return { + required: false, + serializedName: 'GenericUrl', + type: { + name: 'Composite', + className: 'GenericUrl', + modelProperties: { + genericValue: { + required: false, + serializedName: 'generic_value', + type: { + name: 'String' + } + } + } + } + }; +}; + +module.exports = GenericUrl; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.d.ts index d2ec275673bdc..a105800deac0a 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.d.ts @@ -122,11 +122,14 @@ export interface BaseProduct { * The product documentation. * @member {string} maxProductDisplayName Display name of product. * + * @member {string} [genericValue] Generic URL value. + * * @member {string} [odatavalue] URL value. * */ export interface SimpleProduct extends BaseProduct { maxProductDisplayName: string; + genericValue?: string; odatavalue?: string; } @@ -145,6 +148,8 @@ export interface SimpleProduct extends BaseProduct { * * @member {string} maxProductDisplayName Display name of product. * + * @member {string} [genericValue] Generic URL value. + * * @member {string} [odatavalue] URL value. * */ @@ -153,5 +158,18 @@ export interface FlattenParameterGroup { productId: string; description?: string; maxProductDisplayName: string; + genericValue?: string; odatavalue?: string; } + +/** + * @class + * Initializes a new instance of the GenericUrl class. + * @constructor + * The Generic URL. + * @member {string} [genericValue] Generic URL value. + * + */ +export interface GenericUrl { + genericValue?: string; +} diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.js index cca3ddb58adef..b8365a1c50aaa 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/index.js @@ -21,3 +21,4 @@ exports.ResourceCollection = require('./resourceCollection'); exports.BaseProduct = require('./baseProduct'); exports.SimpleProduct = require('./simpleProduct'); exports.FlattenParameterGroup = require('./flattenParameterGroup'); +exports.GenericUrl = require('./genericUrl'); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/simpleProduct.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/simpleProduct.js index 5739ebc390150..3e66a747ff5a0 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/simpleProduct.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/ModelFlattening/models/simpleProduct.js @@ -21,6 +21,8 @@ var util = require('util'); * The product documentation. * @member {string} maxProductDisplayName Display name of product. * + * @member {string} [genericValue] Generic URL value. + * * @member {string} [odatavalue] URL value. * */ @@ -75,6 +77,13 @@ SimpleProduct.prototype.mapper = function () { name: 'String' } }, + genericValue: { + required: false, + serializedName: 'details.max_product_image.generic_value', + type: { + name: 'String' + } + }, odatavalue: { required: false, serializedName: 'details.max_product_image.@odata\\.value', diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts index bda3709eb4178..3d9f5f55e7f91 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/index.d.ts @@ -360,6 +360,40 @@ export interface Paths { */ dateTimeNull(dateTimePath: Date|string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; dateTimeNull(dateTimePath: Date|string, callback: ServiceCallback): void; + + /** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url) + * + * @param {buffer} base64UrlPath base64url encoded value + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + base64Url(base64UrlPath: Buffer, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + base64Url(base64UrlPath: Buffer, callback: ServiceCallback): void; + + /** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, + * ''] using the csv-array format + * + * @param {array} arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ + * &=+$,/?#[]end' , null, ''] using the csv-array format + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {ServiceCallback} [callback] callback function; see ServiceCallback + * doc in ms-rest index.d.ts for details + */ + arrayCsvInPath(arrayPath: string[], options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + arrayCsvInPath(arrayPath: string[], callback: ServiceCallback): void; } /** diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js index 53af0e791fe20..ac14e44e195cb 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Url/operations/paths.js @@ -2247,5 +2247,216 @@ Paths.prototype.dateTimeNull = function (dateTimePath, options, callback) { }); }; +/** + * Get 'lorem' encoded value as 'bG9yZW0' (base64url) + * + * @param {buffer} base64UrlPath base64url encoded value + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {null} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +Paths.prototype.base64Url = function (base64UrlPath, options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + // Validate + try { + if (!Buffer.isBuffer(base64UrlPath)) { + throw new Error('base64UrlPath cannot be null or undefined and it must be of type buffer.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//paths/string/bG9yZW0/{base64UrlPath}'; + requestUrl = requestUrl.replace('{base64UrlPath}', encodeURIComponent(client.serialize({required: true, serializedName: 'base64UrlPath', type: {name: 'Base64Url'}}, base64UrlPath, 'base64UrlPath'))); + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + + return callback(null, result, httpRequest, response); + }); +}; + +/** + * Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, + * ''] using the csv-array format + * + * @param {array} arrayPath an array of string ['ArrayPath1', 'begin!*'();:@ + * &=+$,/?#[]end' , null, ''] using the csv-array format + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.customHeaders] Headers that will be added to the + * request + * + * @param {function} callback + * + * @returns {function} callback(err, result, request, response) + * + * {Error} err - The Error object if an error occurred, null otherwise. + * + * {null} [result] - The deserialized result object. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +Paths.prototype.arrayCsvInPath = function (arrayPath, options, callback) { + var client = this.client; + if(!callback && typeof options === 'function') { + callback = options; + options = null; + } + if (!callback) { + throw new Error('callback cannot be null.'); + } + // Validate + try { + if (!util.isArray(arrayPath)) { + throw new Error('arrayPath cannot be null or undefined and it must be of type array.'); + } + for (var i = 0; i < arrayPath.length; i++) { + if (arrayPath[i] !== null && arrayPath[i] !== undefined && typeof arrayPath[i].valueOf() !== 'string') { + throw new Error('arrayPath[i] must be of type string.'); + } + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath:commaSeparated}'; + requestUrl = requestUrl.replace('{arrayPath:commaSeparated}', encodeURIComponent(arrayPath.toString())); + // trim all duplicate forward slashes in the url + var regex = /([^:]\/)\/+/gi; + requestUrl = requestUrl.replace(regex, '$1'); + + // Create HTTP transport objects + var httpRequest = new WebResource(); + httpRequest.method = 'GET'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if(options) { + for(var headerName in options['customHeaders']) { + if (options['customHeaders'].hasOwnProperty(headerName)) { + httpRequest.headers[headerName] = options['customHeaders'][headerName]; + } + } + } + httpRequest.headers['Content-Type'] = 'application/json; charset=utf-8'; + httpRequest.body = null; + // Send Request + return client.pipeline(httpRequest, function (err, response, responseBody) { + if (err) { + return callback(err); + } + var statusCode = response.statusCode; + if (statusCode !== 200) { + var error = new Error(responseBody); + error.statusCode = response.statusCode; + error.request = msRest.stripRequest(httpRequest); + error.response = msRest.stripResponse(response); + if (responseBody === '') responseBody = null; + var parsedErrorResponse; + try { + parsedErrorResponse = JSON.parse(responseBody); + if (parsedErrorResponse) { + if (parsedErrorResponse.error) parsedErrorResponse = parsedErrorResponse.error; + if (parsedErrorResponse.code) error.code = parsedErrorResponse.code; + if (parsedErrorResponse.message) error.message = parsedErrorResponse.message; + } + if (parsedErrorResponse !== null && parsedErrorResponse !== undefined) { + var resultMapper = new client.models['ErrorModel']().mapper(); + error.body = client.deserialize(resultMapper, parsedErrorResponse, 'error.body'); + } + } catch (defaultError) { + error.message = util.format('Error "%s" occurred in deserializing the responseBody ' + + '- "%s" for the default response.', defaultError.message, responseBody); + return callback(error); + } + return callback(error); + } + // Create Result + var result = null; + if (responseBody === '') responseBody = null; + + return callback(null, result, httpRequest, response); + }); +}; + module.exports = Paths; diff --git a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs index 2b5e72bc5db7b..c842b28b3280b 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs @@ -125,6 +125,12 @@ public static string ToString(this IType type, string reference) return string.Format(CultureInfo.InvariantCulture, "{0}.toISOString()", reference); } + + if (known.Type == KnownPrimaryType.Base64Url) + { + return string.Format(CultureInfo.InvariantCulture, + "client.serialize({{required: true, serializedName: '{0}', type: {{name: 'Base64Url'}}}}, {0}, '{0}')", reference); + } } return string.Format(CultureInfo.InvariantCulture, "{0}.toString()", reference); @@ -236,7 +242,7 @@ private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvid builder.AppendLine("if ({0} !== null && {0} !== undefined && !(typeof {0}.valueOf() === 'string' && msRest.isValidUuid({0}))) {{", valueReference); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } - else if (primary.Type == KnownPrimaryType.ByteArray) + else if (primary.Type == KnownPrimaryType.ByteArray || primary.Type == KnownPrimaryType.Base64Url) { if (isRequired) { @@ -304,7 +310,7 @@ private static string PrimaryTSType(this PrimaryType primary) return "Date"; else if (primary.Type == KnownPrimaryType.Object) return "any"; // TODO: test this - else if (primary.Type == KnownPrimaryType.ByteArray) + else if (primary.Type == KnownPrimaryType.ByteArray || primary.Type == KnownPrimaryType.Base64Url) return "Buffer"; else if (primary.Type == KnownPrimaryType.Stream) return "stream.Readable"; @@ -756,6 +762,10 @@ public static string ConstructMapper(this IType type, string serializedName, IPa { builder.AppendLine("type: {").Indent().AppendLine("name: 'ByteArray'").Outdent().AppendLine("}"); } + else if (primary.Type == KnownPrimaryType.Base64Url) + { + builder.AppendLine("type: {").Indent().AppendLine("name: 'Base64Url'").Outdent().AppendLine("}"); + } else if (primary.Type == KnownPrimaryType.Date) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Date'").Outdent().AppendLine("}"); diff --git a/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs b/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs index bdc9153f1ca06..04bacdaeb59b0 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs @@ -16,7 +16,7 @@ namespace Microsoft.Rest.Generator.NodeJS { public class NodeJSCodeGenerator : CodeGenerator { - private const string ClientRuntimePackage = "ms-rest version 1.10.0"; + private const string ClientRuntimePackage = "ms-rest version 1.12.0"; public NodeJsCodeNamer Namer { get; private set; } diff --git a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs index 907584895d8fd..d2f43a402f589 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs @@ -341,7 +341,11 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) throw new ArgumentNullException("primaryType"); } - if (primaryType.Type == KnownPrimaryType.Boolean) + if (primaryType.Type == KnownPrimaryType.Base64Url) + { + primaryType.Name = "Buffer"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) { primaryType.Name = "Boolean"; } @@ -389,6 +393,10 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) { primaryType.Name = "moment.duration"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + primaryType.Name = "Number"; + } else if (primaryType.Type == KnownPrimaryType.Uuid) { primaryType.Name = "Uuid"; diff --git a/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/MethodTemplateModel.cs index b07c71cfb566b..d5ee24b66c21f 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/MethodTemplateModel.cs @@ -11,6 +11,7 @@ using Microsoft.Rest.Generator.Utilities; using System.Collections; using System.Text; +using System.Text.RegularExpressions; namespace Microsoft.Rest.Generator.NodeJS { @@ -610,7 +611,15 @@ protected virtual void BuildPathParameters(string variableName, IndentedStringBu { pathReplaceFormat = "{0} = {0}.replace('{{{1}}}', {2});"; } - builder.AppendLine(pathReplaceFormat, variableName, pathParameter.SerializedName, + var urlPathName = pathParameter.SerializedName; + string pat = @".*\{" + urlPathName + @"(\:\w+)\}"; + Regex r = new Regex(pat); + Match m = r.Match(Url); + if (m.Success) + { + urlPathName += m.Groups[1].Value; + } + builder.AppendLine(pathReplaceFormat, variableName, urlPathName, pathParameter.Type.ToString(pathParameter.Name)); } } diff --git a/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/ServiceClientTemplateModel.cs b/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/ServiceClientTemplateModel.cs index 577a91bd3e147..ec34d6af04247 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/ServiceClientTemplateModel.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/TemplateModels/ServiceClientTemplateModel.cs @@ -154,13 +154,18 @@ public string RequiredConstructorParameters get { var requireParams = new List(); - this.Properties.Where(p => p.IsRequired && !p.IsConstant) + this.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue)) .ForEach(p => requireParams.Add(p.Name.ToCamelCase())); if (!IsCustomBaseUri) { requireParams.Add("baseUri"); } + if(requireParams == null || requireParams.Count == 0) + { + return string.Empty; + } + return string.Join(", ", requireParams); } } @@ -174,7 +179,7 @@ public string RequiredConstructorParametersTS { bool first = true; foreach (var p in this.Properties) { - if (!p.IsRequired || p.IsConstant) + if (!p.IsRequired || p.IsConstant || (p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue))) continue; if (!first) diff --git a/AutoRest/Generators/NodeJS/NodeJS/Templates/ModelTemplate.cshtml b/AutoRest/Generators/NodeJS/NodeJS/Templates/ModelTemplate.cshtml index 75c9384491c78..9ab35ed94e1e0 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/NodeJS/NodeJS/Templates/ModelTemplate.cshtml @@ -20,11 +20,6 @@ @:var util = require('util'); @EmptyLine } -@if (Model.ContainsDurationProperty()) -{ -@:var moment = require('moment'); -@EmptyLine -} /** * @@class * Initializes a new instance of the @(Model.Name) class. diff --git a/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplate.cshtml b/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplate.cshtml index 07092323c73f6..055038401726b 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplate.cshtml +++ b/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplate.cshtml @@ -37,8 +37,8 @@ var ServiceClient = msRest.ServiceClient; @:var operations = require('./operations'); } @EmptyLine -@{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant);} -@{var optionalParameters = Model.Properties.Where(p => !p.IsRequired && !p.IsConstant);} +@{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue));} +@{var optionalParameters = Model.Properties.Where(p => (!p.IsRequired || p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue)) && !p.IsConstant);} /** * @@class * Initializes a new instance of the @Model.Name class. @@ -71,7 +71,7 @@ var ServiceClient = msRest.ServiceClient; @: * } */ -function @(Model.Name)(@(Model.RequiredConstructorParameters), options) { +function @(Model.Name)(@(!string.IsNullOrEmpty(Model.RequiredConstructorParameters) ? Model.RequiredConstructorParameters + ", ": "")options) { @foreach (var property in Model.Properties.Where(p => p.DefaultValue != null)) { @:this.@(property.Name) = @(property.DefaultValue); @@ -91,11 +91,17 @@ function @(Model.Name)(@(Model.RequiredConstructorParameters), options) { @if(!Model.IsCustomBaseUri) { @:this.baseUri = baseUri; + + @:if (!this.baseUri) { + @:this.baseUri = '@Model.BaseUrl'; + @:} +} +else +{ + @:this.baseUri = '@Model.BaseUrl'; } - if (!this.baseUri) { - this.baseUri = '@Model.BaseUrl'; - } + @foreach (var param in requiredParameters) { diff --git a/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplateTS.cshtml b/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplateTS.cshtml index 61edf0e006279..c9e479a3c95e4 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplateTS.cshtml +++ b/AutoRest/Generators/NodeJS/NodeJS/Templates/ServiceClientTemplateTS.cshtml @@ -18,8 +18,8 @@ import { ServiceClientOptions, RequestOptions, ServiceCallback } from 'ms-rest'; } @EmptyLine declare class @(Model.Name) { - @{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant);} - @{var optionalParameters = Model.Properties.Where(p => !p.IsRequired && !p.IsConstant);} + @{var requiredParameters = Model.Properties.Where(p => p.IsRequired && !p.IsConstant && string.IsNullOrEmpty(p.DefaultValue));} + @{var optionalParameters = Model.Properties.Where(p => (!p.IsRequired || p.IsRequired && !string.IsNullOrEmpty(p.DefaultValue)) && !p.IsConstant);} /** * @@class * Initializes a new instance of the @Model.Name class. @@ -52,7 +52,7 @@ declare class @(Model.Name) { @: * } */ - constructor(@(Model.RequiredConstructorParametersTS), options: ServiceClientOptions); + constructor(@(!string.IsNullOrEmpty(Model.RequiredConstructorParametersTS) ? Model.RequiredConstructorParametersTS + ", ": "")options: ServiceClientOptions); @foreach (var property in Model.Properties) { diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/AcceptanceTests/lro_tests.py b/AutoRest/Generators/Python/Azure.Python.Tests/AcceptanceTests/lro_tests.py index ba72f0477c7b3..7e52e686bda1a 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/AcceptanceTests/lro_tests.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/AcceptanceTests/lro_tests.py @@ -102,16 +102,16 @@ def test_lro_happy_paths(self): # Testing raw process = self.client.lr_os.put201_creating_succeeded200(product, raw=True) - self.assertEqual("Succeeded", process.result().output.provisioning_state) + self.assertEqual("Creating", process.output.provisioning_state) - self.assertRaisesWithMessage("Long running operation failed", - self.client.lr_os.put201_creating_failed200(product, raw=True).result) + process = self.client.lr_os.put201_creating_failed200(product, raw=True) + self.assertEqual("Created", process.output.provisioning_state) process = self.client.lr_os.put200_updating_succeeded204(product, raw=True) - self.assertEqual("Succeeded", process.result().output.provisioning_state) + self.assertEqual("Updating", process.output.provisioning_state) - self.assertRaisesWithMessage("Long running operation failed", - self.client.lr_os.put200_acceptedcanceled200(product, raw=True).result) + process = self.client.lr_os.put200_acceptedcanceled200(product, raw=True) + self.assertEqual("Accepted", process.output.provisioning_state) process = self.client.lr_os.put_no_header_in_retry(product) self.assertEqual("Succeeded", process.result().provisioning_state) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py index bceee986fdda8..668b135381e1f 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/auto_rest_duration_test_service.py @@ -43,7 +43,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/autorestdurationtestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/setup.py index 386a34a84a195..251a4cda74c35 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureBodyDuration/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py index b8bae0b1b5228..13e63f9569c81 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/auto_rest_parameter_grouping_test_service.py @@ -43,7 +43,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/first_parameter_group.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/first_parameter_group.py index bd178f8128ba4..0a3174e49ea52 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/first_parameter_group.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/first_parameter_group.py @@ -22,6 +22,6 @@ class FirstParameterGroup(Model): :type query_one: int """ - def __init__(self, header_one=None, query_one=30, **kwargs): + def __init__(self, header_one=None, query_one=30): self.header_one = header_one self.query_one = query_one diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_multi_param_groups_second_param_group.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_multi_param_groups_second_param_group.py index e885a9124d948..d178c7470903e 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_multi_param_groups_second_param_group.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_multi_param_groups_second_param_group.py @@ -22,6 +22,6 @@ class ParameterGroupingPostMultiParamGroupsSecondParamGroup(Model): :type query_two: int """ - def __init__(self, header_two=None, query_two=30, **kwargs): + def __init__(self, header_two=None, query_two=30): self.header_two = header_two self.query_two = query_two diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_optional_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_optional_parameters.py index a89e6b36d00b3..7368af7d84956 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_optional_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_optional_parameters.py @@ -22,6 +22,6 @@ class ParameterGroupingPostOptionalParameters(Model): :type query: int """ - def __init__(self, custom_header=None, query=30, **kwargs): + def __init__(self, custom_header=None, query=30): self.custom_header = custom_header self.query = query diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_required_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_required_parameters.py index 56ec95284747e..33627d834bdad 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_required_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/autorestparametergroupingtestservice/models/parameter_grouping_post_required_parameters.py @@ -31,7 +31,7 @@ class ParameterGroupingPostRequiredParameters(Model): 'path': {'required': True}, } - def __init__(self, body, path, custom_header=None, query=30, **kwargs): + def __init__(self, body, path, custom_header=None, query=30): self.body = body self.custom_header = custom_header self.query = query diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/setup.py index 188c79aaea4bf..2e0910c9bcdeb 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureParameterGrouping/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py index b37530e7d7985..c02088e43b1a4 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/auto_rest_report_service_for_azure.py @@ -44,7 +44,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/autorestreportserviceforazure/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/setup.py index b088cbdc514b9..762429f51c290 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureReport/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py index 3a806d13f53fc..74f09db9d3400 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py @@ -44,7 +44,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py index 019aa228b5d07..37bf31568e6ae 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/flattened_product.py @@ -15,16 +15,19 @@ class FlattenedProduct(Resource): """FlattenedProduct - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str :param pname: :type pname: str :param lsize: @@ -33,6 +36,12 @@ class FlattenedProduct(Resource): :type provisioning_state: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -44,8 +53,8 @@ class FlattenedProduct(Resource): 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, lsize=None, provisioning_state=None, **kwargs): - super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name, **kwargs) + def __init__(self, tags=None, location=None, pname=None, lsize=None, provisioning_state=None): + super(FlattenedProduct, self).__init__(tags=tags, location=location) self.pname = pname self.lsize = lsize self.provisioning_state = provisioning_state diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py index c2e81e8035ee3..349e6b7fbd717 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource.py @@ -15,18 +15,27 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -35,9 +44,9 @@ class Resource(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, **kwargs): - self.id = id - self.type = type + def __init__(self, tags=None, location=None): + self.id = None + self.type = None self.tags = tags self.location = location - self.name = name + self.name = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource_collection.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource_collection.py index ce97251d6b01a..4c59a75395942 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource_collection.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/autorestresourceflatteningtestservice/models/resource_collection.py @@ -31,7 +31,7 @@ class ResourceCollection(Model): 'dictionaryofresources': {'key': 'dictionaryofresources', 'type': '{FlattenedProduct}'}, } - def __init__(self, productresource=None, arrayofresources=None, dictionaryofresources=None, **kwargs): + def __init__(self, productresource=None, arrayofresources=None, dictionaryofresources=None): self.productresource = productresource self.arrayofresources = arrayofresources self.dictionaryofresources = dictionaryofresources diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/setup.py index 93b7b7f8b4bd8..d4003cb22d3fd 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureResource/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py index cc2d96c0ce719..95f2d47d0fb58 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/auto_rest_azure_special_parameters_test_client.py @@ -56,9 +56,15 @@ def __init__( self, credentials, subscription_id, api_version='2015-07-01-preview', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/error.py index b4ab713953874..e9ef780e3aefa 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/error.py @@ -30,7 +30,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, constant_id=None, message=None, **kwargs): + def __init__(self, status=None, constant_id=None, message=None): self.status = status self.constant_id = constant_id self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/odata_filter.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/odata_filter.py index a0604d9f6045b..16c1f6545d148 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/odata_filter.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/autorestazurespecialparameterstestclient/models/odata_filter.py @@ -26,6 +26,6 @@ class OdataFilter(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/setup.py index 581909f4464b6..a23f56d19161d 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/AzureSpecials/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py index ce9c7112afaf5..79e862f82db73 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py @@ -45,9 +45,13 @@ def __init__( self, credentials, host, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if host is None: - raise ValueError('host must not be None.') + raise ValueError("Parameter 'host' must not be None.") + if not isinstance(host, str): + raise TypeError("Parameter 'host' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") base_url = 'http://{accountName}{host}' super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(base_url, filepath) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py index d7a4a945847f1..b58762d14bf16 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py index 85044ec1cbcc4..fc86a3308cb2e 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/autorestheadtestservice/auto_rest_head_test_service.py @@ -42,7 +42,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/setup.py index 8fd8508a288a8..e11e2311eb413 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Head/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py index e7531777378d2..d9745572729ef 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/autorestheadexceptiontestservice/auto_rest_head_exception_test_service.py @@ -42,7 +42,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/setup.py index 94a2cb8cb8860..eea7127ecba39 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/HeadExceptions/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py index 718b1114d10af..be1ddc0cc63c0 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/auto_rest_long_running_operation_test_service.py @@ -46,7 +46,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result.py index 21fd4883dc37e..2ded58b2f5920 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result.py @@ -29,6 +29,6 @@ class OperationResult(Model): 'error': {'key': 'error', 'type': 'OperationResultError'}, } - def __init__(self, status=None, error=None, **kwargs): + def __init__(self, status=None, error=None): self.status = status self.error = error diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result_error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result_error.py index 974649001b44e..22dab4495c979 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result_error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/operation_result_error.py @@ -26,6 +26,6 @@ class OperationResultError(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, code=None, message=None, **kwargs): + def __init__(self, code=None, message=None): self.code = code self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py index db52ee8ddc946..1671df6f6c655 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/product.py @@ -15,24 +15,34 @@ class Product(Resource): """Product - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str :param provisioning_state: :type provisioning_state: str - :param provisioning_state_values: Possible values include: 'Succeeded', + :ivar provisioning_state_values: Possible values include: 'Succeeded', 'Failed', 'canceled', 'Accepted', 'Creating', 'Created', 'Updating', 'Updated', 'Deleting', 'Deleted', 'OK' - :type provisioning_state_values: str + :vartype provisioning_state_values: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + 'provisioning_state_values': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -43,7 +53,7 @@ class Product(Resource): 'provisioning_state_values': {'key': 'properties.provisioningStateValues', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, provisioning_state=None, provisioning_state_values=None, **kwargs): - super(Product, self).__init__(id=id, type=type, tags=tags, location=location, name=name, **kwargs) + def __init__(self, tags=None, location=None, provisioning_state=None): + super(Product, self).__init__(tags=tags, location=location) self.provisioning_state = provisioning_state - self.provisioning_state_values = provisioning_state_values + self.provisioning_state_values = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py index c2e81e8035ee3..349e6b7fbd717 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/resource.py @@ -15,18 +15,27 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -35,9 +44,9 @@ class Resource(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, **kwargs): - self.id = id - self.type = type + def __init__(self, tags=None, location=None): + self.id = None + self.type = None self.tags = tags self.location = location - self.name = name + self.name = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sku.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sku.py index 42b14cd43755d..d7f35d777f639 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sku.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sku.py @@ -26,6 +26,6 @@ class Sku(Model): 'id': {'key': 'id', 'type': 'str'}, } - def __init__(self, name=None, id=None, **kwargs): + def __init__(self, name=None, id=None): self.name = name self.id = id diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py index a0bc26f58f22e..c813566223b8d 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_product.py @@ -15,23 +15,31 @@ class SubProduct(SubResource): """SubProduct - :param id: Sub Resource Id - :type id: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Sub Resource Id + :vartype id: str :param provisioning_state: :type provisioning_state: str - :param provisioning_state_values: Possible values include: 'Succeeded', + :ivar provisioning_state_values: Possible values include: 'Succeeded', 'Failed', 'canceled', 'Accepted', 'Creating', 'Created', 'Updating', 'Updated', 'Deleting', 'Deleted', 'OK' - :type provisioning_state_values: str + :vartype provisioning_state_values: str """ + _validation = { + 'id': {'readonly': True}, + 'provisioning_state_values': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'provisioning_state_values': {'key': 'properties.provisioningStateValues', 'type': 'str'}, } - def __init__(self, id=None, provisioning_state=None, provisioning_state_values=None, **kwargs): - super(SubProduct, self).__init__(id=id, **kwargs) + def __init__(self, provisioning_state=None): + super(SubProduct, self).__init__() self.provisioning_state = provisioning_state - self.provisioning_state_values = provisioning_state_values + self.provisioning_state_values = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py index 83b7f418cbe93..77ec6cf29f437 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/models/sub_resource.py @@ -15,13 +15,20 @@ class SubResource(Model): """SubResource - :param id: Sub Resource Id - :type id: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Sub Resource Id + :vartype id: str """ + _validation = { + 'id': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, } - def __init__(self, id=None, **kwargs): - self.id = id + def __init__(self): + self.id = None diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py index 79e601f333e0c..96ade6d8e3ad8 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_custom_header_operations.py @@ -49,14 +49,12 @@ def put_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/customheader/putasync/retry/succeeded' @@ -119,6 +117,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -141,14 +143,12 @@ def put201_creating_succeeded200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/customheader/put/201/creating/succeeded/200' @@ -206,6 +206,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -228,13 +232,11 @@ def post202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/customheader/post/202/retry/200' @@ -287,6 +289,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -309,13 +315,11 @@ def post_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/customheader/postasync/retry/succeeded' @@ -369,6 +373,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py index f5c417d272ed2..4a078a8a86f8f 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lr_os_operations.py @@ -46,14 +46,12 @@ def put200_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/put/200/succeeded' @@ -109,6 +107,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -129,14 +131,12 @@ def put200_succeeded_no_state( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/put/200/succeeded/nostate' @@ -192,6 +192,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -212,14 +216,12 @@ def put202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/put/202/retry/200' @@ -275,6 +277,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -296,14 +302,12 @@ def put201_creating_succeeded200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/put/201/creating/succeeded/200' @@ -361,6 +365,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -382,14 +390,12 @@ def put200_updating_succeeded204( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/put/200/updating/succeeded/200' @@ -445,6 +451,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -466,14 +476,12 @@ def put201_creating_failed200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/put/201/created/failed/200' @@ -531,6 +539,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -552,14 +564,12 @@ def put200_acceptedcanceled200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/put/200/accepted/canceled/200' @@ -615,6 +625,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -635,14 +649,12 @@ def put_no_header_in_retry( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/put/noheader/202/200' @@ -703,6 +715,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -724,14 +740,12 @@ def put_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/putasync/retry/succeeded' @@ -794,6 +808,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -815,14 +833,12 @@ def put_async_no_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/putasync/noretry/succeeded' @@ -884,6 +900,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -905,14 +925,12 @@ def put_async_retry_failed( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/putasync/retry/failed' @@ -975,6 +993,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -996,14 +1018,12 @@ def put_async_no_retrycanceled( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/putasync/noretry/canceled' @@ -1065,6 +1085,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1085,14 +1109,12 @@ def put_async_no_header_in_retry( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/putasync/noheader/201/200' @@ -1153,6 +1175,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1170,14 +1196,12 @@ def put_non_resource( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Sku - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Sku + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/putnonresource/202/200' @@ -1233,6 +1257,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1250,14 +1278,12 @@ def put_async_non_resource( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Sku - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Sku + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/putnonresourceasync/202/200' @@ -1313,6 +1339,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1331,14 +1361,12 @@ def put_sub_resource( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`SubProduct - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`SubProduct + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/putsubresource/202/200' @@ -1394,6 +1422,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1412,14 +1444,12 @@ def put_async_sub_resource( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`SubProduct - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`SubProduct + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/putsubresourceasync/202/200' @@ -1475,6 +1505,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1493,14 +1527,12 @@ def delete_provisioning202_accepted200_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/delete/provisioning/202/accepted/200/succeeded' @@ -1561,6 +1593,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1579,14 +1615,12 @@ def delete_provisioning202_deleting_failed200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/delete/provisioning/202/deleting/200/failed' @@ -1647,6 +1681,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1665,14 +1703,12 @@ def delete_provisioning202_deletingcanceled200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/delete/provisioning/202/deleting/200/canceled' @@ -1733,6 +1769,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1748,13 +1788,11 @@ def delete204_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/delete/204/succeeded' @@ -1796,6 +1834,10 @@ def get_long_running_output(response): client_raw_response = ClientRawResponse(None, response) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1813,14 +1855,12 @@ def delete202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/delete/202/retry/200' @@ -1875,6 +1915,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1892,14 +1936,12 @@ def delete202_no_retry204( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/delete/202/noretry/204' @@ -1954,6 +1996,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1971,13 +2017,11 @@ def delete_no_header_in_retry( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/delete/noheader' @@ -2022,6 +2066,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2039,13 +2087,11 @@ def delete_async_no_header_in_retry( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/deleteasync/noheader/202/204' @@ -2090,6 +2136,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2107,13 +2157,11 @@ def delete_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/deleteasync/retry/succeeded' @@ -2160,6 +2208,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2177,13 +2229,11 @@ def delete_async_no_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/deleteasync/noretry/succeeded' @@ -2230,6 +2280,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2247,13 +2301,11 @@ def delete_async_retry_failed( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/deleteasync/retry/failed' @@ -2300,6 +2352,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2317,13 +2373,11 @@ def delete_async_retrycanceled( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/deleteasync/retry/canceled' @@ -2370,6 +2424,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2387,14 +2445,12 @@ def post200_with_payload( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Sku - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Sku + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/post/payload/200' @@ -2445,6 +2501,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2465,13 +2525,11 @@ def post202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/post/202/retry/200' @@ -2524,6 +2582,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2544,14 +2606,12 @@ def post202_no_retry204( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/post/202/noretry/204' @@ -2613,6 +2673,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2634,14 +2698,12 @@ def post_async_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/postasync/retry/succeeded' @@ -2704,6 +2766,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2725,14 +2791,12 @@ def post_async_no_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/postasync/noretry/succeeded' @@ -2795,6 +2859,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2816,13 +2884,11 @@ def post_async_retry_failed( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/postasync/retry/failed' @@ -2876,6 +2942,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -2897,13 +2967,11 @@ def post_async_retrycanceled( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/postasync/retry/canceled' @@ -2957,6 +3025,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py index c6512164959df..786c3c3bf6d7d 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lro_retrys_operations.py @@ -48,14 +48,12 @@ def put201_creating_succeeded200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/retryerror/put/201/creating/succeeded/200' @@ -113,6 +111,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -134,14 +136,12 @@ def put_async_relative_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/retryerror/putasync/retry/succeeded' @@ -204,6 +204,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -222,14 +226,12 @@ def delete_provisioning202_accepted200_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/retryerror/delete/provisioning/202/accepted/200/succeeded' @@ -290,6 +292,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -307,13 +313,11 @@ def delete202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/retryerror/delete/202/retry/200' @@ -359,6 +363,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -376,13 +384,11 @@ def delete_async_relative_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/retryerror/deleteasync/retry/succeeded' @@ -429,6 +435,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -449,13 +459,11 @@ def post202_retry200( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/retryerror/post/202/retry/200' @@ -508,6 +516,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -529,13 +541,11 @@ def post_async_relative_retry_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/retryerror/postasync/retry/succeeded' @@ -589,6 +599,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py index b02cf952e3e91..f4bb777cedec5 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/autorestlongrunningoperationtestservice/operations/lrosa_ds_operations.py @@ -45,14 +45,12 @@ def put_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/nonretryerror/put/400' @@ -110,6 +108,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -129,14 +131,12 @@ def put_non_retry201_creating400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/nonretryerror/put/201/creating/400' @@ -194,6 +194,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -214,14 +218,12 @@ def put_async_relative_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/nonretryerror/putasync/retry/400' @@ -284,6 +286,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -299,13 +305,11 @@ def delete_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/nonretryerror/delete/400' @@ -351,6 +355,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -367,13 +375,11 @@ def delete202_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/nonretryerror/delete/202/retry/400' @@ -419,6 +425,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -436,13 +446,11 @@ def delete_async_relative_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/nonretryerror/deleteasync/retry/400' @@ -489,6 +497,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -507,13 +519,11 @@ def post_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/nonretryerror/post/400' @@ -566,6 +576,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -584,13 +598,11 @@ def post202_non_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/nonretryerror/post/202/retry/400' @@ -643,6 +655,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -663,13 +679,11 @@ def post_async_relative_retry400( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/nonretryerror/postasync/retry/400' @@ -723,6 +737,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -742,14 +760,12 @@ def put_error201_no_provisioning_state_payload( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/put/201/noprovisioningstatepayload' @@ -807,6 +823,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -828,14 +848,12 @@ def put_async_relative_retry_no_status( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/putasync/retry/nostatus' @@ -898,6 +916,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -919,14 +941,12 @@ def put_async_relative_retry_no_status_payload( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/putasync/retry/nostatuspayload' @@ -989,6 +1009,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1005,13 +1029,11 @@ def delete204_succeeded( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/delete/204/nolocation' @@ -1053,6 +1075,10 @@ def get_long_running_output(response): client_raw_response = ClientRawResponse(None, response) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1070,13 +1096,11 @@ def delete_async_relative_retry_no_status( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/deleteasync/retry/nostatus' @@ -1123,6 +1147,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1142,13 +1170,11 @@ def post202_no_location( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/post/202/nolocation' @@ -1201,6 +1227,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1222,13 +1252,11 @@ def post_async_relative_retry_no_payload( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/postasync/retry/nopayload' @@ -1282,6 +1310,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1301,14 +1333,12 @@ def put200_invalid_json( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/put/200/invalidjson' @@ -1364,6 +1394,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1384,14 +1418,12 @@ def put_async_relative_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/putasync/retry/invalidheader' @@ -1454,6 +1486,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1475,14 +1511,12 @@ def put_async_relative_retry_invalid_json_polling( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`Product - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/putasync/retry/invalidjsonpolling' @@ -1545,6 +1579,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1562,13 +1600,11 @@ def delete202_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/delete/202/retry/invalidheader' @@ -1614,6 +1650,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1631,13 +1671,11 @@ def delete_async_relative_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/deleteasync/retry/invalidheader' @@ -1684,6 +1722,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1701,13 +1743,11 @@ def delete_async_relative_retry_invalid_json_polling( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/deleteasync/retry/invalidjsonpolling' @@ -1754,6 +1794,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1773,13 +1817,11 @@ def post202_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/post/202/retry/invalidheader' @@ -1832,6 +1874,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1852,13 +1898,11 @@ def post_async_relative_retry_invalid_header( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/postasync/retry/invalidheader' @@ -1912,6 +1956,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) @@ -1933,13 +1981,11 @@ def post_async_relative_retry_invalid_json_polling( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return None or - :class:`ClientRawResponse` if - raw=true + instance that returns None + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/lro/error/postasync/retry/invalidjsonpolling' @@ -1993,6 +2039,10 @@ def get_long_running_output(response): }) return client_raw_response + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/setup.py index 3d6569fed9a9e..6efdcd0d3ea4e 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Lro/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py index 532adc38d5acc..e3cf9310642ed 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/auto_rest_paging_test_service.py @@ -43,7 +43,9 @@ def __init__( self, credentials, accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/operation_result.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/operation_result.py index 13b86a98343d8..e0af748f82c9f 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/operation_result.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/operation_result.py @@ -25,5 +25,5 @@ class OperationResult(Model): 'status': {'key': 'status', 'type': 'str'}, } - def __init__(self, status=None, **kwargs): + def __init__(self, status=None): self.status = status diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_options.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_options.py index c91f754fee26f..c776b4da879d7 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_options.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_options.py @@ -25,6 +25,6 @@ class PagingGetMultiplePagesOptions(Model): :type timeout: int """ - def __init__(self, maxresults=None, timeout=30, **kwargs): + def __init__(self, maxresults=None, timeout=30): self.maxresults = maxresults self.timeout = timeout diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_with_offset_options.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_with_offset_options.py index cdb588109cda7..57650f8519648 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_with_offset_options.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/paging_get_multiple_pages_with_offset_options.py @@ -31,7 +31,7 @@ class PagingGetMultiplePagesWithOffsetOptions(Model): 'offset': {'required': True}, } - def __init__(self, offset, maxresults=None, timeout=30, **kwargs): + def __init__(self, offset, maxresults=None, timeout=30): self.maxresults = maxresults self.offset = offset self.timeout = timeout diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product.py index d9babb6925957..f019f46d72e5a 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product.py @@ -24,5 +24,5 @@ class Product(Model): 'properties': {'key': 'properties', 'type': 'ProductProperties'}, } - def __init__(self, properties=None, **kwargs): + def __init__(self, properties=None): self.properties = properties diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product_properties.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product_properties.py index 2924fa9464303..4db1d4204a78d 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product_properties.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/autorestpagingtestservice/models/product_properties.py @@ -26,6 +26,6 @@ class ProductProperties(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/setup.py index a02653a9cb33b..b8c042a69efb9 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/Paging/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/setup.py index 100c1f03a42f3..7e7b4160e02e1 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/bar.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/bar.py index dd61b74f50851..09c2ed766ed61 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/bar.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/bar.py @@ -26,5 +26,5 @@ class Bar(Model): 'recursive_point': {'key': 'RecursivePoint', 'type': 'Endpoints'}, } - def __init__(self, recursive_point=None, **kwargs): + def __init__(self, recursive_point=None): self.recursive_point = recursive_point diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/check_name_availability_result.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/check_name_availability_result.py index 2626b7d6d9408..cc1c87848bdf4 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/check_name_availability_result.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/check_name_availability_result.py @@ -35,7 +35,7 @@ class CheckNameAvailabilityResult(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, name_available=None, reason=None, message=None, **kwargs): + def __init__(self, name_available=None, reason=None, message=None): self.name_available = name_available self.reason = reason self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/custom_domain.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/custom_domain.py index e94b86210a007..f23bf8e6696ec 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/custom_domain.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/custom_domain.py @@ -30,6 +30,6 @@ class CustomDomain(Model): 'use_sub_domain': {'key': 'useSubDomain', 'type': 'bool'}, } - def __init__(self, name=None, use_sub_domain=None, **kwargs): + def __init__(self, name=None, use_sub_domain=None): self.name = name self.use_sub_domain = use_sub_domain diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/endpoints.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/endpoints.py index 18e67db15f0e1..898527a5c8db1 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/endpoints.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/endpoints.py @@ -39,7 +39,7 @@ class Endpoints(Model): 'foo_point': {'key': 'FooPoint', 'type': 'Foo'}, } - def __init__(self, blob=None, queue=None, table=None, dummy_end_point=None, foo_point=None, **kwargs): + def __init__(self, blob=None, queue=None, table=None, dummy_end_point=None, foo_point=None): self.blob = blob self.queue = queue self.table = table diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/foo.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/foo.py index 91428f1689ace..2de0ad72c8366 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/foo.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/foo.py @@ -26,5 +26,5 @@ class Foo(Model): 'bar_point': {'key': 'Bar.Point', 'type': 'Bar'}, } - def __init__(self, bar_point=None, **kwargs): + def __init__(self, bar_point=None): self.bar_point = bar_point diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py index d9358ccfb3f05..8d25c5c02f7ac 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/resource.py @@ -15,12 +15,15 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -28,6 +31,9 @@ class Resource(Model): """ _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, 'location': {'required': True}, } @@ -39,9 +45,9 @@ class Resource(Model): 'tags': {'key': 'tags', 'type': '{str}'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, **kwargs): - self.id = id - self.name = name - self.type = type + def __init__(self, location, tags=None): + self.id = None + self.name = None + self.type = None self.location = location self.tags = tags diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py index b565b7120cee1..bff1707d78076 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account.py @@ -16,12 +16,15 @@ class StorageAccount(Resource): """ The storage account. - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -77,6 +80,9 @@ class StorageAccount(Resource): """ _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, 'location': {'required': True}, } @@ -99,8 +105,8 @@ class StorageAccount(Resource): 'secondary_endpoints': {'key': 'properties.secondaryEndpoints', 'type': 'Endpoints'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None, **kwargs): - super(StorageAccount, self).__init__(id=id, name=name, type=type, location=location, tags=tags, **kwargs) + def __init__(self, location, tags=None, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None): + super(StorageAccount, self).__init__(location=location, tags=tags) self.provisioning_state = provisioning_state self.account_type = account_type self.primary_endpoints = primary_endpoints diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_check_name_availability_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_check_name_availability_parameters.py index 7fd37db107159..3874804d1acce 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_check_name_availability_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_check_name_availability_parameters.py @@ -30,6 +30,6 @@ class StorageAccountCheckNameAvailabilityParameters(Model): 'type': {'key': 'type', 'type': 'str'}, } - def __init__(self, name, type="Microsoft.Storage/storageAccounts", **kwargs): + def __init__(self, name, type="Microsoft.Storage/storageAccounts"): self.name = name self.type = type diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py index e4de00fde6c84..31535a2dc8c20 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_create_parameters.py @@ -16,12 +16,15 @@ class StorageAccountCreateParameters(Resource): """ The parameters to provide for the account. - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -33,6 +36,9 @@ class StorageAccountCreateParameters(Resource): """ _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, 'location': {'required': True}, } @@ -45,6 +51,6 @@ class StorageAccountCreateParameters(Resource): 'account_type': {'key': 'properties.accountType', 'type': 'AccountType'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, account_type=None, **kwargs): - super(StorageAccountCreateParameters, self).__init__(id=id, name=name, type=type, location=location, tags=tags, **kwargs) + def __init__(self, location, tags=None, account_type=None): + super(StorageAccountCreateParameters, self).__init__(location=location, tags=tags) self.account_type = account_type diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_keys.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_keys.py index 6a3d1413b9f3d..6a49f862ea08c 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_keys.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_keys.py @@ -27,6 +27,6 @@ class StorageAccountKeys(Model): 'key2': {'key': 'key2', 'type': 'str'}, } - def __init__(self, key1=None, key2=None, **kwargs): + def __init__(self, key1=None, key2=None): self.key1 = key1 self.key2 = key2 diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_regenerate_key_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_regenerate_key_parameters.py index f4c0bd5893004..7fe2da5d56729 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_regenerate_key_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_regenerate_key_parameters.py @@ -23,5 +23,5 @@ class StorageAccountRegenerateKeyParameters(Model): 'key_name': {'key': 'keyName', 'type': 'KeyName'}, } - def __init__(self, key_name=None, **kwargs): + def __init__(self, key_name=None): self.key_name = key_name diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py index 1a4b634650561..e60b187d613bd 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/storage_account_update_parameters.py @@ -16,12 +16,15 @@ class StorageAccountUpdateParameters(Resource): """ The parameters to update on the account. - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -41,6 +44,9 @@ class StorageAccountUpdateParameters(Resource): """ _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, 'location': {'required': True}, } @@ -54,7 +60,7 @@ class StorageAccountUpdateParameters(Resource): 'custom_domain': {'key': 'properties.customDomain', 'type': 'CustomDomain'}, } - def __init__(self, location, id=None, name=None, type=None, tags=None, account_type=None, custom_domain=None, **kwargs): - super(StorageAccountUpdateParameters, self).__init__(id=id, name=name, type=type, location=location, tags=tags, **kwargs) + def __init__(self, location, tags=None, account_type=None, custom_domain=None): + super(StorageAccountUpdateParameters, self).__init__(location=location, tags=tags) self.account_type = account_type self.custom_domain = custom_domain diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/sub_resource.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/sub_resource.py index 4daf061642fbf..676b7409deec4 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/sub_resource.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/sub_resource.py @@ -23,5 +23,5 @@ class SubResource(Model): 'id': {'key': 'id', 'type': 'str'}, } - def __init__(self, id=None, **kwargs): + def __init__(self, id=None): self.id = id diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage.py index 3be6b28966e34..53d96b70adf16 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage.py @@ -38,7 +38,7 @@ class Usage(Model): 'name': {'key': 'name', 'type': 'UsageName'}, } - def __init__(self, unit=None, current_value=None, limit=None, name=None, **kwargs): + def __init__(self, unit=None, current_value=None, limit=None, name=None): self.unit = unit self.current_value = current_value self.limit = limit diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_list_result.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_list_result.py index bb868e0c1633d..58bcc17497530 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_list_result.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_list_result.py @@ -25,5 +25,5 @@ class UsageListResult(Model): 'value': {'key': 'value', 'type': '[Usage]'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_name.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_name.py index 920db4d98eeeb..91e050893c0f9 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_name.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/models/usage_name.py @@ -28,6 +28,6 @@ class UsageName(Model): 'localized_value': {'key': 'localizedValue', 'type': 'str'}, } - def __init__(self, value=None, localized_value=None, **kwargs): + def __init__(self, value=None, localized_value=None): self.value = value self.localized_value = localized_value diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py index 424d097b470fe..2250ab10c1468 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/operations/storage_accounts_operations.py @@ -124,14 +124,12 @@ def create( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`StorageAccount + instance that returns :class:`StorageAccount ` - or :class:`ClientRawResponse` if - raw=true + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' @@ -191,6 +189,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py index cd2c457915195..1334ec94142ec 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/StorageManagementClient/storagemanagementclient/storage_management_client.py @@ -50,9 +50,15 @@ def __init__( self, credentials, subscription_id, api_version='2015-05-01-preview', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://management.azure.com' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py index 99e3bc1f4ce98..d16f3f25706a6 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/microsoft_azure_test_url.py @@ -47,9 +47,15 @@ def __init__( self, credentials, subscription_id, api_version='2014-04-01-preview', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://management.azure.com/' diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/error.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/error.py index e85f2c415d577..9b230ca9dee62 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/error.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, code=None, message=None, **kwargs): + def __init__(self, code=None, message=None): self.code = code self.message = message diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/sample_resource_group.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/sample_resource_group.py index f2a334ff424c4..19fa537a1bea8 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/sample_resource_group.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/microsoftazuretesturl/models/sample_resource_group.py @@ -26,6 +26,6 @@ class SampleResourceGroup(Model): 'location': {'key': 'location', 'type': 'str'}, } - def __init__(self, name=None, location=None, **kwargs): + def __init__(self, name=None, location=None): self.name = name self.location = location diff --git a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/setup.py b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/setup.py index 0d026fe2b27f5..a0eeb22b2beda 100644 --- a/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/setup.py +++ b/AutoRest/Generators/Python/Azure.Python.Tests/Expected/AcceptanceTests/SubscriptionIdApiVersion/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Azure.Python/AzurePythonCodeGenerator.cs b/AutoRest/Generators/Python/Azure.Python/AzurePythonCodeGenerator.cs index fb90e029585e1..0ad15558928b5 100644 --- a/AutoRest/Generators/Python/Azure.Python/AzurePythonCodeGenerator.cs +++ b/AutoRest/Generators/Python/Azure.Python/AzurePythonCodeGenerator.cs @@ -19,7 +19,7 @@ namespace Microsoft.Rest.Generator.Azure.Python { public class AzurePythonCodeGenerator : PythonCodeGenerator { - private const string ClientRuntimePackage = "msrestazure version 0.1.0"; + private const string ClientRuntimePackage = "msrestazure version 0.2.1"; // page extensions class dictionary. private IList pageModels; diff --git a/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs b/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs index 145dbeb3a79ae..f56bc3935547a 100644 --- a/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs +++ b/AutoRest/Generators/Python/Azure.Python/TemplateModels/AzureServiceClientTemplateModel.cs @@ -74,7 +74,7 @@ public override string RequiredConstructorParameters else { string defaultValue = PythonConstants.None; - if (property.DefaultValue != null && property.Type is PrimaryType) + if (!string.IsNullOrWhiteSpace(property.DefaultValue) && property.Type is PrimaryType) { defaultValue = property.DefaultValue; } @@ -97,7 +97,7 @@ public override string SetupRequires { get { - return "\"msrest>=0.1.0\", \"msrestazure>=0.1.0\""; + return "\"msrest>=0.2.0\", \"msrestazure>=0.2.1\""; } } diff --git a/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml b/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml index edb91f8ea7a02..78533cd451225 100644 --- a/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml +++ b/AutoRest/Generators/Python/Azure.Python/Templates/AzureLongRunningMethodTemplate.cshtml @@ -31,9 +31,8 @@ @: @ParameterWrapComment(string.Empty, ":param callback: When specified, will be called with each chunk of data that is streamed. The callback should take two arguments, the bytes of the current chunk of data and the response object. If the data is uploading, response will be None.") @: @ParameterWrapComment(string.Empty, ":type callback: Callable[Bytes, response=None]") } - @ParameterWrapComment(string.Empty, ":param operation_config: :ref:`Operation configuration overrides`.") - @ParameterWrapComment(string.Empty, ":rtype: :class:`AzureOperationPoller`") - @ParameterWrapComment(string.Empty, ":return: A poller object which can return " + Model.GetDocumentationType(Model.ReturnType.Body) + " or :class:`ClientRawResponse` if raw=true") + @ParameterWrapComment(string.Empty, ":rtype: :class:`AzureOperationPoller` instance that returns " + Model.GetDocumentationType(Model.ReturnType.Body)) + @ParameterWrapComment(string.Empty, ":rtype: :class:`ClientRawResponse` if raw=true") """ @Model.BuildInputMappings() @if (Model.InputParameterTransformation.Any()) @@ -140,6 +139,10 @@ else { @:@Model.ReturnEmptyResponse } +@EmptyLine + if raw: + response = long_running_send() + return get_long_running_output(response) @EmptyLine long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/complex_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/complex_tests.py index fcbf2f38617cf..fa4902659e391 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/complex_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/complex_tests.py @@ -201,6 +201,19 @@ def test_complex(self): # PUT primitive/byte client.primitive.put_byte(valid_bytes) + """ + COMPLEX TYPE WITH READ ONLY PROPERTIES + """ + # GET readonly/valid + valid_obj = ReadonlyObj(size=2) + valid_obj.id = '1234' + readonly_result = client.readonlyproperty.get_valid() + self.assertEqual(readonly_result, valid_obj) + + # PUT readonly/valid + readonly_result = client.readonlyproperty.put_valid(valid_obj) + self.assertIsNone(readonly_result) + """ COMPLEX TYPE WITH ARRAY PROPERTIES """ diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py index cc7fb8d0f5eb7..900265a4ed1fe 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/file_tests.py @@ -53,24 +53,21 @@ class FileTests(unittest.TestCase): def test_files(self): config = AutoRestSwaggerBATFileServiceConfiguration(base_url="http://localhost:3000") - config.log_level = log_level config.connection.data_block_size = 1000 client = AutoRestSwaggerBATFileService(config) - def test_callback(data, response, progress = [0], is_response_streamed=None): + def test_callback(data, response, progress=[0]): self.assertTrue(len(data) > 0) - if not is_response_streamed: - self.assertFalse(response._content_consumed) + self.assertIsNotNone(response) + self.assertFalse(response._content_consumed) + total = float(response.headers['Content-Length']) + if total < 4096: progress[0] += len(data) - total = float(response.headers['Content-Length']) print("Downloading... {}%".format(int(progress[0]*100/total))) - self.assertIsNotNone(response) file_length = 0 with io.BytesIO() as file_handle: - - stream = client.files.get_file(callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + stream = client.files.get_file(callback=test_callback) for data in stream: file_length += len(data) @@ -86,11 +83,10 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): sample_data = hash(data.read()) self.assertEqual(sample_data, hash(file_handle.getvalue())) + config.connection.data_block_size = 4096 file_length = 0 with io.BytesIO() as file_handle: - - stream = client.files.get_empty_file(callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + stream = client.files.get_empty_file(callback=test_callback) for data in stream: file_length += len(data) @@ -98,9 +94,12 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): self.assertEqual(file_length, 0) - #file_length = 0 - #stream = client.files.get_file_large(callback=lambda x, response, progress=[0] : - # test_callback(x, response, progress, True)) + def add_headers(adapter, request, response, *args, **kwargs): + response.headers['Content-Length'] = str(3000 * 1024 * 1024) + + file_length = 0 + client._client.add_hook('response', add_headers) + stream = client.files.get_file_large(callback=test_callback) #for data in stream: # file_length += len(data) @@ -108,24 +107,21 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): def test_files_raw(self): - def test_callback(data, response, progress = [0], is_response_streamed=None): + def test_callback(data, response, progress=[0]): self.assertTrue(len(data) > 0) - if not is_response_streamed: - self.assertFalse(response._content_consumed) + self.assertIsNotNone(response) + self.assertFalse(response._content_consumed) + total = float(response.headers.get('Content-Length', 0)) + if total: progress[0] += len(data) - total = float(response.headers['Content-Length']) print("Downloading... {}%".format(int(progress[0]*100/total))) - self.assertIsNotNone(response) config = AutoRestSwaggerBATFileServiceConfiguration(base_url="http://localhost:3000") - config.log_level = log_level client = AutoRestSwaggerBATFileService(config) file_length = 0 with io.BytesIO() as file_handle: - - response = client.files.get_file(raw=True, callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + response = client.files.get_file(raw=True, callback=test_callback) stream = response.output for data in stream: @@ -144,9 +140,7 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): file_length = 0 with io.BytesIO() as file_handle: - - response = client.files.get_empty_file(raw=True, callback=lambda x, response, progress=[0] : - test_callback(x, response, progress, False)) + response = client.files.get_empty_file(raw=True, callback=test_callback) stream = response.output for data in stream: @@ -155,16 +149,5 @@ def test_callback(data, response, progress = [0], is_response_streamed=None): self.assertEqual(file_length, 0) - #file_length = 0 - #response = client.files.get_file_large(raw=True, callback=lambda x, response, progress=[0] : - # test_callback(x, response, progress, True)) - - #stream = response.output - - #for data in stream: - # file_length += len(data) - - #self.assertEqual(file_length, 3000 * 1024 * 1024) - if __name__ == '__main__': unittest.main() \ No newline at end of file diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py index f18bfdb92aa05..ea1ed1a726f9e 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/form_data_tests.py @@ -174,7 +174,6 @@ def test_callback(data, response, progress = [0]): with open(self.dummy_file, 'rb') as upload_data: resp = client.formdata.upload_file_via_body(upload_data, callback=test_callback) for r in resp: - print(r) result.write(r) self.assertEqual(result.getvalue().decode(), "Test file") diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/model_flattening_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/model_flattening_tests.py index 470b6d2d677ff..f15c8d90a2c92 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/model_flattening_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/model_flattening_tests.py @@ -222,7 +222,8 @@ def test_model_flattening_simple(self): product_id = "123", description = "product description", max_product_display_name = "max name", - odatavalue = "http://foo" + odatavalue = "http://foo", + generic_value = "https://generic" ) result = self.client.put_simple_product(simple_prduct) @@ -237,7 +238,7 @@ def test_model_flattening_with_parameter_flattening(self): odatavalue = "http://foo" ) - result = self.client.post_flattened_simple_product("123", "max name", "product description", "http://foo") + result = self.client.post_flattened_simple_product("123", "max name", "product description", None, "http://foo") self.assertEqual(result, simple_product) def test_model_flattening_with_grouping(self): diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py index 4cba849ad212a..3204669e8568c 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/url_tests.py @@ -91,6 +91,9 @@ def test_url_path(self): self.client.paths.get_ten_billion(10000000000) self.client.paths.string_empty("") + test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] + self.client.paths.array_csv_in_path(test_array) + with self.assertRaises(ValidationError): self.client.paths.string_null(None) diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/validation_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/validation_tests.py index 5af07d6773dbd..7e1ba54e0556e 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/validation_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/validation_tests.py @@ -67,10 +67,7 @@ def test_constant_values(self): client.get_with_constant_in_path() - # TODO: Const body should be built implicitly body = Product(child=ChildProduct()) - body.const_child = ConstantProduct() - product = client.post_with_constant_in_body(body=body) self.assertIsNotNone(product) @@ -121,7 +118,6 @@ def test_validation(self): try: tempproduct=Product(child=ChildProduct(), capacity=0) - tempproduct.const_child=ConstantProduct() client.validation_of_body("123", 150, tempproduct) except ValidationError as err: self.assertEqual(err.rule, "minimum_ex") @@ -129,7 +125,6 @@ def test_validation(self): try: tempproduct=Product(child=ChildProduct(), capacity=100) - tempproduct.const_child=ConstantProduct() client.validation_of_body("123", 150, tempproduct) except ValidationError as err: self.assertEqual(err.rule, "maximum_ex") @@ -138,7 +133,6 @@ def test_validation(self): try: tempproduct=Product(child=ChildProduct(), display_names=["item1","item2","item3","item4","item5","item6","item7"]) - tempproduct.const_child=ConstantProduct() client.validation_of_body("123", 150, tempproduct) except ValidationError as err: self.assertEqual(err.rule, "max_items") @@ -155,4 +149,8 @@ def test_validation(self): client2.validation_of_method_parameters("123", 150) except ValidationError as err: self.assertEqual(err.rule, "pattern") - self.assertEqual(err.target, "self.config.api_version") \ No newline at end of file + self.assertEqual(err.target, "self.config.api_version") + + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py index 3702f08cd4316..2afd6aa9c3c70 100644 --- a/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py +++ b/AutoRest/Generators/Python/Python.Tests/AcceptanceTests/zzz_tests.py @@ -53,30 +53,38 @@ def test_ensure_coverage(self): config.log_level = log_level client = AutoRestReportService(config) report = client.get_report() - report['getIntegerOverflow']=1 - report['getIntegerUnderflow']=1 - report['getLongOverflow']=1 - report['getLongUnderflow']=1 - report['getDateInvalid']=1 - report['getDictionaryNullkey']=1 - report['HttpRedirect300Get']=1 - report['FileStreamVeryLarge']=1 - - # TODO: Support ignore readonly property in http put - report['putComplexReadOnlyPropertyValid']=1 - - skipped = [k for k, v in report.items() if v == 0] - manually_marked_successful = [k for k, v in report.items() if v == 2] - for s in manually_marked_successful: - print("SKIPPED {0}".format(s)) - - for s in skipped: + + # Add tests that wont be supported due to the nature of Python here + not_supported = { + 'getIntegerOverflow': 1, + 'getIntegerUnderflow': 1, + 'getLongOverflow': 1, + 'getLongUnderflow': 1, + 'getDateInvalid': 1, + 'getDictionaryNullkey': 1, + 'HttpRedirect300Get': 1, + } + + # Please add missing features or failing tests here + missing_features_or_bugs = {'FileStreamVeryLarge' : 1} + + report.update(not_supported) + report.update(missing_features_or_bugs) + failed = [k for k, v in report.items() if v == 0] + + for s in not_supported.keys(): + print("IGNORING {0}".format(s)) + + for s in missing_features_or_bugs.keys(): + print("PENDING {0}".format(s)) + + for s in failed: print("FAILED TO EXECUTE {0}".format(s)) totalTests = len(report) - print ("The test coverage is {0}/{1}.".format(totalTests - len(skipped), totalTests)) + print ("The test coverage is {0}/{1}.".format(totalTests - len(failed), totalTests)) - self.assertEqual(0, len(skipped)) + self.assertEqual(0, len(failed)) if __name__ == '__main__': unittest.main() diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/product.py index 3358c74205436..b74b8ee418307 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/models/product.py @@ -26,6 +26,6 @@ class Product(Model): 'string': {'key': 'string', 'type': 'str'}, } - def __init__(self, integer=None, string=None, **kwargs): + def __init__(self, integer=None, string=None): self.integer = integer self.string = string diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/operations/array.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/operations/array.py index 1a94ea14d19e8..1d437ec67f879 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/operations/array.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/autorestswaggerbatarrayservice/operations/array.py @@ -2053,6 +2053,51 @@ def get_byte_invalid_null( return deserialized + def get_base64_url( + self, custom_headers={}, raw=False, **operation_config): + """ + Get array value ['a string that gets encoded with base64url', 'test + string' 'Lorem ipsum'] with the items base64url encoded + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: list of str + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/array/prim/base64url/valid' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('[str]', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + def get_complex_null( self, custom_headers={}, raw=False, **operation_config): """ diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/setup.py index db9a2a12116a5..cf329dfab37c5 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyArray/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/autorestbooltestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/autorestbooltestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/autorestbooltestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/autorestbooltestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/setup.py index 8058a2eff9ed9..facfec90a0b4c 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyBoolean/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/autorestswaggerbatbyteservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/autorestswaggerbatbyteservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/autorestswaggerbatbyteservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/autorestswaggerbatbyteservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/setup.py index 38ae3533fae8d..0482b6833f373 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyByte/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py index 8ff86db017bbd..3887687ac962c 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/auto_rest_complex_test_service.py @@ -38,7 +38,9 @@ def __init__( self, api_version, base_url=None, filepath=None): if api_version is None: - raise ValueError('api_version must not be None.') + raise ValueError("Parameter 'api_version' must not be None.") + if not isinstance(api_version, str): + raise TypeError("Parameter 'api_version' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/array_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/array_wrapper.py index 954d370a66c94..df8448a8fbea8 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/array_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/array_wrapper.py @@ -23,5 +23,5 @@ class ArrayWrapper(Model): 'array': {'key': 'array', 'type': '[str]'}, } - def __init__(self, array=None, **kwargs): + def __init__(self, array=None): self.array = array diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/basic.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/basic.py index 0f914a9ac9030..83a9721456ac7 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/basic.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/basic.py @@ -30,7 +30,7 @@ class Basic(Model): 'color': {'key': 'color', 'type': 'CMYKColors'}, } - def __init__(self, id=None, name=None, color=None, **kwargs): + def __init__(self, id=None, name=None, color=None): self.id = id self.name = name self.color = color diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/boolean_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/boolean_wrapper.py index 89429bc9bc429..abe1f9cb4e232 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/boolean_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/boolean_wrapper.py @@ -26,6 +26,6 @@ class BooleanWrapper(Model): 'field_false': {'key': 'field_false', 'type': 'bool'}, } - def __init__(self, field_true=None, field_false=None, **kwargs): + def __init__(self, field_true=None, field_false=None): self.field_true = field_true self.field_false = field_false diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/byte_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/byte_wrapper.py index 505b230b7c2f7..56711e83f0787 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/byte_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/byte_wrapper.py @@ -23,5 +23,5 @@ class ByteWrapper(Model): 'field': {'key': 'field', 'type': 'bytearray'}, } - def __init__(self, field=None, **kwargs): + def __init__(self, field=None): self.field = field diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cat.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cat.py index 476c2a0c1d028..15ec946bab6d2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cat.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cat.py @@ -33,7 +33,7 @@ class Cat(Pet): 'hates': {'key': 'hates', 'type': '[Dog]'}, } - def __init__(self, id=None, name=None, color=None, hates=None, **kwargs): - super(Cat, self).__init__(id=id, name=name, **kwargs) + def __init__(self, id=None, name=None, color=None, hates=None): + super(Cat, self).__init__(id=id, name=name) self.color = color self.hates = hates diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cookiecuttershark.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cookiecuttershark.py index ee898dd7d3582..835f078e28c02 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cookiecuttershark.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/cookiecuttershark.py @@ -36,6 +36,6 @@ class Cookiecuttershark(Shark): 'birthday': {'required': True}, } - def __init__(self, length, birthday, species=None, siblings=None, age=None, **kwargs): - super(Cookiecuttershark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday, **kwargs) + def __init__(self, length, birthday, species=None, siblings=None, age=None): + super(Cookiecuttershark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday) self.fishtype = 'cookiecuttershark' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/date_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/date_wrapper.py index 03b379e1105c7..d876dc6e736c8 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/date_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/date_wrapper.py @@ -26,6 +26,6 @@ class DateWrapper(Model): 'leap': {'key': 'leap', 'type': 'date'}, } - def __init__(self, field=None, leap=None, **kwargs): + def __init__(self, field=None, leap=None): self.field = field self.leap = leap diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetime_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetime_wrapper.py index 74e8645ace21d..c768499e011f9 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetime_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetime_wrapper.py @@ -26,6 +26,6 @@ class DatetimeWrapper(Model): 'now': {'key': 'now', 'type': 'iso-8601'}, } - def __init__(self, field=None, now=None, **kwargs): + def __init__(self, field=None, now=None): self.field = field self.now = now diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetimerfc1123_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetimerfc1123_wrapper.py index 165fdceb85a3c..a0279c5425f7c 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetimerfc1123_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/datetimerfc1123_wrapper.py @@ -26,6 +26,6 @@ class Datetimerfc1123Wrapper(Model): 'now': {'key': 'now', 'type': 'rfc-1123'}, } - def __init__(self, field=None, now=None, **kwargs): + def __init__(self, field=None, now=None): self.field = field self.now = now diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dictionary_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dictionary_wrapper.py index e639e709ab1d9..999fec60f3d96 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dictionary_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dictionary_wrapper.py @@ -23,5 +23,5 @@ class DictionaryWrapper(Model): 'default_program': {'key': 'defaultProgram', 'type': '{str}'}, } - def __init__(self, default_program=None, **kwargs): + def __init__(self, default_program=None): self.default_program = default_program diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dog.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dog.py index 69911b3d30437..420352f5b0eb5 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dog.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/dog.py @@ -29,6 +29,6 @@ class Dog(Pet): 'food': {'key': 'food', 'type': 'str'}, } - def __init__(self, id=None, name=None, food=None, **kwargs): - super(Dog, self).__init__(id=id, name=name, **kwargs) + def __init__(self, id=None, name=None, food=None): + super(Dog, self).__init__(id=id, name=name) self.food = food diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/double_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/double_wrapper.py index 5eb718fcc08e7..63f46bd155bd0 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/double_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/double_wrapper.py @@ -29,6 +29,6 @@ class DoubleWrapper(Model): 'field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose': {'key': 'field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose', 'type': 'float'}, } - def __init__(self, field1=None, field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose=None, **kwargs): + def __init__(self, field1=None, field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose=None): self.field1 = field1 self.field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose = field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/duration_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/duration_wrapper.py index ce5cd3ce54403..04cfa5a36c7d2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/duration_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/duration_wrapper.py @@ -23,5 +23,5 @@ class DurationWrapper(Model): 'field': {'key': 'field', 'type': 'duration'}, } - def __init__(self, field=None, **kwargs): + def __init__(self, field=None): self.field = field diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/fish.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/fish.py index f1aea273aefb1..fb83f8e3fa972 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/fish.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/fish.py @@ -42,7 +42,7 @@ class Fish(Model): 'fishtype': {'salmon': 'Salmon', 'shark': 'Shark'} } - def __init__(self, length, species=None, siblings=None, **kwargs): + def __init__(self, length, species=None, siblings=None): self.species = species self.length = length self.siblings = siblings diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/float_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/float_wrapper.py index 52350aacd388a..098ff503ef763 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/float_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/float_wrapper.py @@ -26,6 +26,6 @@ class FloatWrapper(Model): 'field2': {'key': 'field2', 'type': 'float'}, } - def __init__(self, field1=None, field2=None, **kwargs): + def __init__(self, field1=None, field2=None): self.field1 = field1 self.field2 = field2 diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/goblinshark.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/goblinshark.py index c9cf046ed0cb5..a119ee4d6e574 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/goblinshark.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/goblinshark.py @@ -48,7 +48,7 @@ class Goblinshark(Shark): 'jawsize': {'key': 'jawsize', 'type': 'int'}, } - def __init__(self, length, birthday, species=None, siblings=None, age=None, jawsize=None, **kwargs): - super(Goblinshark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday, **kwargs) + def __init__(self, length, birthday, species=None, siblings=None, age=None, jawsize=None): + super(Goblinshark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday) self.jawsize = jawsize self.fishtype = 'goblin' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/int_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/int_wrapper.py index ad9a60209e698..92136de6442c0 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/int_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/int_wrapper.py @@ -26,6 +26,6 @@ class IntWrapper(Model): 'field2': {'key': 'field2', 'type': 'int'}, } - def __init__(self, field1=None, field2=None, **kwargs): + def __init__(self, field1=None, field2=None): self.field1 = field1 self.field2 = field2 diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/long_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/long_wrapper.py index 350dff72efff5..70a8c78b56d3b 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/long_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/long_wrapper.py @@ -26,6 +26,6 @@ class LongWrapper(Model): 'field2': {'key': 'field2', 'type': 'long'}, } - def __init__(self, field1=None, field2=None, **kwargs): + def __init__(self, field1=None, field2=None): self.field1 = field1 self.field2 = field2 diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/pet.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/pet.py index f637af26154de..ae794dc5f6338 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/pet.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/pet.py @@ -26,6 +26,6 @@ class Pet(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py index 54f617ab191ec..109d15efbe7e4 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/readonly_obj.py @@ -15,17 +15,24 @@ class ReadonlyObj(Model): """ReadonlyObj - :param id: - :type id: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: + :vartype id: str :param size: :type size: int """ + _validation = { + 'id': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'size': {'key': 'size', 'type': 'int'}, } - def __init__(self, id=None, size=None, **kwargs): - self.id = id + def __init__(self, size=None): + self.id = None self.size = size diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/salmon.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/salmon.py index 94073cb2b7e36..ca9ac00e67109 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/salmon.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/salmon.py @@ -44,8 +44,8 @@ class Salmon(Fish): 'iswild': {'key': 'iswild', 'type': 'bool'}, } - def __init__(self, length, species=None, siblings=None, location=None, iswild=None, **kwargs): - super(Salmon, self).__init__(species=species, length=length, siblings=siblings, **kwargs) + def __init__(self, length, species=None, siblings=None, location=None, iswild=None): + super(Salmon, self).__init__(species=species, length=length, siblings=siblings) self.location = location self.iswild = iswild self.fishtype = 'salmon' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/sawshark.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/sawshark.py index 9666b532506da..eb5f018fd759b 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/sawshark.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/sawshark.py @@ -48,7 +48,7 @@ class Sawshark(Shark): 'picture': {'key': 'picture', 'type': 'bytearray'}, } - def __init__(self, length, birthday, species=None, siblings=None, age=None, picture=None, **kwargs): - super(Sawshark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday, **kwargs) + def __init__(self, length, birthday, species=None, siblings=None, age=None, picture=None): + super(Sawshark, self).__init__(species=species, length=length, siblings=siblings, age=age, birthday=birthday) self.picture = picture self.fishtype = 'sawshark' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/shark.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/shark.py index 51fe0956bf51d..18d4187ebede9 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/shark.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/shark.py @@ -49,8 +49,8 @@ class Shark(Fish): 'fishtype': {'sawshark': 'Sawshark', 'goblin': 'Goblinshark', 'cookiecuttershark': 'Cookiecuttershark'} } - def __init__(self, length, birthday, species=None, siblings=None, age=None, **kwargs): - super(Shark, self).__init__(species=species, length=length, siblings=siblings, **kwargs) + def __init__(self, length, birthday, species=None, siblings=None, age=None): + super(Shark, self).__init__(species=species, length=length, siblings=siblings) self.age = age self.birthday = birthday self.fishtype = 'shark' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/siamese.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/siamese.py index a52c0d69892b1..ad83ab4771cf1 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/siamese.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/siamese.py @@ -36,6 +36,6 @@ class Siamese(Cat): 'breed': {'key': 'breed', 'type': 'str'}, } - def __init__(self, id=None, name=None, color=None, hates=None, breed=None, **kwargs): - super(Siamese, self).__init__(id=id, name=name, color=color, hates=hates, **kwargs) + def __init__(self, id=None, name=None, color=None, hates=None, breed=None): + super(Siamese, self).__init__(id=id, name=name, color=color, hates=hates) self.breed = breed diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/string_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/string_wrapper.py index 19bb78f4673a5..a01f361cdba21 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/string_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/autorestcomplextestservice/models/string_wrapper.py @@ -29,7 +29,7 @@ class StringWrapper(Model): 'null': {'key': 'null', 'type': 'str'}, } - def __init__(self, field=None, empty=None, null=None, **kwargs): + def __init__(self, field=None, empty=None, null=None): self.field = field self.empty = empty self.null = null diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/setup.py index c67f7c49a7562..65d0a41a65f59 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyComplex/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/autorestdatetestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/autorestdatetestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/autorestdatetestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/autorestdatetestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/setup.py index 09e6aa6e8c9ef..c70f0e8100516 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDate/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/autorestdatetimetestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/autorestdatetimetestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/autorestdatetimetestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/autorestdatetimetestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/setup.py index 420c600dff136..ac383e8eb0acb 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTime/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/autorestrfc1123datetimetestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/autorestrfc1123datetimetestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/autorestrfc1123datetimetestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/autorestrfc1123datetimetestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/setup.py index b323ed157ce25..143969182ad02 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDateTimeRfc1123/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/widget.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/widget.py index 3ac8dcf6034e4..3a3c86f698dd4 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/widget.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/models/widget.py @@ -26,6 +26,6 @@ class Widget(Model): 'string': {'key': 'string', 'type': 'str'}, } - def __init__(self, integer=None, string=None, **kwargs): + def __init__(self, integer=None, string=None): self.integer = integer self.string = string diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary.py index dbe5fd33141ad..55fd8ef1953dc 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/autorestswaggerbatdictionaryservice/operations/dictionary.py @@ -2058,6 +2058,51 @@ def get_byte_invalid_null( return deserialized + def get_base64_url( + self, custom_headers={}, raw=False, **operation_config): + """ + Get base64url dictionary value {"0": "a string that gets encoded with + base64url", "1": "test string", "2": "Lorem ipsum"} + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: dict + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/dictionary/prim/base64url/valid' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('{str}', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + def get_complex_null( self, custom_headers={}, raw=False, **operation_config): """ diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/setup.py index 6dcd5850b3d44..3326b76166d12 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDictionary/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/autorestdurationtestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/autorestdurationtestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/autorestdurationtestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/autorestdurationtestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/setup.py index 3340f8db5b9cd..88bb6938d4a09 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyDuration/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/autorestswaggerbatfileservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/autorestswaggerbatfileservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/autorestswaggerbatfileservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/autorestswaggerbatfileservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/setup.py index 918eb67dcd7c0..ff524cfed3430 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFile/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/autorestswaggerbatformdataservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/autorestswaggerbatformdataservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/autorestswaggerbatformdataservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/autorestswaggerbatformdataservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/setup.py index 03d887addbd35..f71daa3028819 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyFormData/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/setup.py index a85431ad534e1..c203877495320 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/autorestnumbertestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/autorestnumbertestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/autorestnumbertestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/autorestnumbertestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/setup.py index 2948a18b3e493..7495879ab1b3f 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyNumber/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/operations/string.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/operations/string.py index 8db69b8a580dc..5910495329f88 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/operations/string.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/autorestswaggerbatservice/operations/string.py @@ -436,3 +436,178 @@ def get_not_provided( return client_raw_response return deserialized + + def get_base64_encoded( + self, custom_headers={}, raw=False, **operation_config): + """ + Get value that is base64 encoded + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: str + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/string/base64Encoding' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('str', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + + def get_base64_url_encoded( + self, custom_headers={}, raw=False, **operation_config): + """ + Get value that is base64url encoded + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: str + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/string/base64UrlEncoding' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('str', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + + def put_base64_url_encoded( + self, string_body, custom_headers={}, raw=False, **operation_config): + """ + Put value that is base64url encoded + + :param string_body: + :type string_body: str + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: None + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/string/base64UrlEncoding' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct body + body_content = self._serialize.body(string_body, 'str') + + # Construct and send request + request = self._client.put(url, query_parameters) + response = self._client.send( + request, header_parameters, body_content, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + if raw: + client_raw_response = ClientRawResponse(None, response) + return client_raw_response + + def get_null_base64_url_encoded( + self, custom_headers={}, raw=False, **operation_config): + """ + Get null value that is expected to be base64url encoded + + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: str + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/string/nullBase64UrlEncoding' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('str', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/setup.py index adcf15f154920..26c1dc8c835ef 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyString/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py index 570afdaa95129..5839338b5a2d2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/auto_rest_parameterized_host_test_client.py @@ -31,7 +31,9 @@ def __init__( self, host, filepath=None): if host is None: - raise ValueError('host must not be None.') + raise ValueError("Parameter 'host' must not be None.") + if not isinstance(host, str): + raise TypeError("Parameter 'host' must be str.") base_url = 'http://{accountName}{host}' super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(base_url, filepath) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/autorestparameterizedhosttestclient/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py index bb4a542940856..20758a3b0efba 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUri/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/__init__.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/__init__.py new file mode 100644 index 0000000000000..6711cf5b14df9 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/__init__.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from .auto_rest_parameterized_custom_host_test_client import AutoRestParameterizedCustomHostTestClient, AutoRestParameterizedCustomHostTestClientConfiguration +from .version import VERSION + +__all__ = [ + 'AutoRestParameterizedCustomHostTestClient', + 'AutoRestParameterizedCustomHostTestClientConfiguration' +] + +__version__ = VERSION + diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/auto_rest_parameterized_custom_host_test_client.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/auto_rest_parameterized_custom_host_test_client.py new file mode 100644 index 0000000000000..6a61d697f46ef --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/auto_rest_parameterized_custom_host_test_client.py @@ -0,0 +1,73 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.service_client import ServiceClient +from msrest import Configuration, Serializer, Deserializer +from .version import VERSION +from .operations.paths import Paths +from . import models + + +class AutoRestParameterizedCustomHostTestClientConfiguration(Configuration): + """Configuration for AutoRestParameterizedCustomHostTestClient + Note that all parameters used to create this instance are saved as instance + attributes. + + :param subscription_id: The subscription id with value 'test12'. + :type subscription_id: str + :param dns_suffix: A string value that is used as a global part of the + parameterized host. Default value 'host'. + :type dns_suffix: str + :param str filepath: Existing config + """ + + def __init__( + self, subscription_id, dns_suffix, filepath=None): + + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if dns_suffix is None: + raise ValueError("Parameter 'dns_suffix' must not be None.") + if not isinstance(dns_suffix, str): + raise TypeError("Parameter 'dns_suffix' must be str.") + base_url = '{vault}{secret}{dnsSuffix}' + + super(AutoRestParameterizedCustomHostTestClientConfiguration, self).__init__(base_url, filepath) + + self.add_user_agent('autorestparameterizedcustomhosttestclient/{}'.format(VERSION)) + + self.subscription_id = subscription_id + self.dns_suffix = dns_suffix + + +class AutoRestParameterizedCustomHostTestClient(object): + """Test Infrastructure for AutoRest + + :param config: Configuration for client. + :type config: AutoRestParameterizedCustomHostTestClientConfiguration + + :ivar paths: Paths operations + :vartype paths: .operations.Paths + """ + + def __init__(self, config): + + self._client = ServiceClient(None, config) + + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + self._serialize = Serializer() + self._deserialize = Deserializer(client_models) + + self.config = config + self.paths = Paths( + self._client, self.config, self._serialize, self._deserialize) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/credentials.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/credentials.py new file mode 100644 index 0000000000000..0d097b4f2a6cf --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/credentials.py @@ -0,0 +1,15 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.authentication import ( + BasicAuthentication, + BasicTokenAuthentication, + OAuthTokenAuthentication) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/exceptions.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/exceptions.py new file mode 100644 index 0000000000000..c3cc00226060c --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/exceptions.py @@ -0,0 +1,21 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.exceptions import ( + ClientException, + SerializationError, + DeserializationError, + TokenExpiredError, + ClientRequestError, + AuthenticationError, + HttpOperationError, + ValidationError, +) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/__init__.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/__init__.py new file mode 100644 index 0000000000000..fd6d517a47113 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/__init__.py @@ -0,0 +1,16 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from .error import Error, ErrorException + +__all__ = [ + 'Error', 'ErrorException', +] diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/error.py new file mode 100644 index 0000000000000..c2d19e377e004 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/error.py @@ -0,0 +1,44 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.serialization import Model +from msrest.exceptions import HttpOperationError + + +class Error(Model): + """Error + + :param status: + :type status: int + :param message: + :type message: str + """ + + _attribute_map = { + 'status': {'key': 'status', 'type': 'int'}, + 'message': {'key': 'message', 'type': 'str'}, + } + + def __init__(self, status=None, message=None): + self.status = status + self.message = message + + +class ErrorException(HttpOperationError): + """Server responsed with exception of type: 'Error'. + + :param deserialize: A deserializer + :param response: Server response to be deserialized. + """ + + def __init__(self, deserialize, response, *args): + + super(ErrorException, self).__init__(deserialize, response, 'Error', *args) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/__init__.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/__init__.py new file mode 100644 index 0000000000000..fa4a82a28df55 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/__init__.py @@ -0,0 +1,16 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from .paths import Paths + +__all__ = [ + 'Paths', +] diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/paths.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/paths.py new file mode 100644 index 0000000000000..2c43f455f742d --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/paths.py @@ -0,0 +1,87 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.pipeline import ClientRawResponse + +from .. import models + + +class Paths(object): + """Paths operations. + + :param client: Client for service requests. + :param config: Configuration of service client. + :param serializer: An object model serializer. + :param deserializer: An objec model deserializer. + """ + + def __init__(self, client, config, serializer, deserializer): + + self._client = client + self._serialize = serializer + self._deserialize = deserializer + + self.config = config + + def get_empty( + self, vault, secret, key_name, key_version="v1", custom_headers={}, raw=False, **operation_config): + """ + Get a 200 to test a valid base uri + + :param vault: The vault name, e.g. https://myvault + :type vault: str + :param secret: Secret value. + :type secret: str + :param key_name: The key name with value 'key1'. + :type key_name: str + :param key_version: The key version. Default value 'v1'. + :type key_version: str + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: None + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/customuri/{subscriptionId}/{keyName}' + path_format_arguments = { + 'vault': self._serialize.url("vault", vault, 'str', skip_quote=True), + 'secret': self._serialize.url("secret", secret, 'str', skip_quote=True), + 'dnsSuffix': self._serialize.url("self.config.dns_suffix", self.config.dns_suffix, 'str', skip_quote=True), + 'keyName': self._serialize.url("key_name", key_name, 'str'), + 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} + if key_version is not None: + query_parameters['keyVersion'] = self._serialize.query("key_version", key_version, 'str') + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + if raw: + client_raw_response = ClientRawResponse(None, response) + return client_raw_response diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/version.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/version.py new file mode 100644 index 0000000000000..a39916c162cec --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/version.py @@ -0,0 +1,13 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +VERSION = "1.0.0" + diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/setup.py new file mode 100644 index 0000000000000..3521fb6abef92 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/setup.py @@ -0,0 +1,40 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- +# coding: utf-8 + +from setuptools import setup, find_packages + +NAME = "autorestparameterizedcustomhosttestclient" +VERSION = "1.0.0" + +# To install the library, run the following +# +# python setup.py install +# +# prerequisite: setuptools +# http://pypi.python.org/pypi/setuptools + +REQUIRES = ["msrest>=0.2.0"] + +setup( + name=NAME, + version=VERSION, + description="AutoRestParameterizedCustomHostTestClient", + author_email="", + url="", + keywords=["Swagger", "AutoRestParameterizedCustomHostTestClient"], + install_requires=REQUIRES, + packages=find_packages(), + include_package_data=True, + long_description="""\ + Test Infrastructure for AutoRest + """ +) diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/autorestswaggerbatheaderservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/autorestswaggerbatheaderservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/autorestswaggerbatheaderservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/autorestswaggerbatheaderservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/setup.py index bf58eae79e6c9..2e773b93aad57 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Header/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/a.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/a.py index 291d1604b627f..f6baf6ea42b4c 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/a.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/a.py @@ -24,7 +24,7 @@ class A(Model): 'status_code': {'key': 'statusCode', 'type': 'str'}, } - def __init__(self, status_code=None, **kwargs): + def __init__(self, status_code=None): self.status_code = status_code diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/b.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/b.py index 4b73a497c8406..0853087e7d476 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/b.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/b.py @@ -26,6 +26,6 @@ class B(A): 'text_status_code': {'key': 'textStatusCode', 'type': 'str'}, } - def __init__(self, status_code=None, text_status_code=None, **kwargs): - super(B, self).__init__(status_code=status_code, **kwargs) + def __init__(self, status_code=None, text_status_code=None): + super(B, self).__init__(status_code=status_code) self.text_status_code = text_status_code diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/c.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/c.py index ec12dffd7884a..2e23c31e92048 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/c.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/c.py @@ -23,5 +23,5 @@ class C(Model): 'http_code': {'key': 'httpCode', 'type': 'str'}, } - def __init__(self, http_code=None, **kwargs): + def __init__(self, http_code=None): self.http_code = http_code diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/d.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/d.py index 3e08e4489c52a..8b32eef124a99 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/d.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/d.py @@ -23,5 +23,5 @@ class D(Model): 'http_status_code': {'key': 'httpStatusCode', 'type': 'str'}, } - def __init__(self, http_status_code=None, **kwargs): + def __init__(self, http_status_code=None): self.http_status_code = http_status_code diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/autoresthttpinfrastructuretestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/setup.py index 2db682d7ec3dc..e08efb221837d 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Http/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py index 1d5dd84a24db8..b0a90b0981ec1 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/auto_rest_resource_flattening_test_service.py @@ -384,7 +384,7 @@ def put_simple_product( return deserialized def post_flattened_simple_product( - self, product_id, max_product_display_name, description=None, odatavalue=None, custom_headers={}, raw=False, **operation_config): + self, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None, custom_headers={}, raw=False, **operation_config): """ Put Flattened Simple Product with client flattening true on the parameter @@ -397,6 +397,8 @@ def post_flattened_simple_product( :type max_product_display_name: str :param description: Description of product. :type description: str + :param generic_value: Generic URL value. + :type generic_value: str :param odatavalue: URL value. :type odatavalue: str :param dict custom_headers: headers that will be added to the request @@ -410,8 +412,8 @@ def post_flattened_simple_product( if raw=true """ simple_body_product = None - if product_id is not None or description is not None or max_product_display_name is not None or odatavalue is not None: - simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, odatavalue=odatavalue) + if product_id is not None or description is not None or max_product_display_name is not None or generic_value is not None or odatavalue is not None: + simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, generic_value=generic_value, odatavalue=odatavalue) # Construct URL url = '/model-flatten/customFlattening' @@ -481,12 +483,15 @@ def put_simple_product_with_grouping( max_product_display_name = None if flatten_parameter_group is not None: max_product_display_name = flatten_parameter_group.max_product_display_name + generic_value = None + if flatten_parameter_group is not None: + generic_value = flatten_parameter_group.generic_value odatavalue = None if flatten_parameter_group is not None: odatavalue = flatten_parameter_group.odatavalue simple_body_product = None - if product_id is not None or description is not None or max_product_display_name is not None or odatavalue is not None: - simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, odatavalue=odatavalue) + if product_id is not None or description is not None or max_product_display_name is not None or generic_value is not None or odatavalue is not None: + simple_body_product = models.SimpleProduct(product_id=product_id, description=description, max_product_display_name=max_product_display_name, generic_value=generic_value, odatavalue=odatavalue) # Construct URL url = '/model-flatten/customFlattening/parametergrouping/{name}/' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/__init__.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/__init__.py index e9fee8e3c065c..0696da7e2b659 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/__init__.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/__init__.py @@ -16,6 +16,7 @@ from .base_product import BaseProduct from .simple_product import SimpleProduct from .flatten_parameter_group import FlattenParameterGroup +from .generic_url import GenericUrl __all__ = [ 'Error', 'ErrorException', @@ -25,4 +26,5 @@ 'BaseProduct', 'SimpleProduct', 'FlattenParameterGroup', + 'GenericUrl', ] diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/base_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/base_product.py index 55707c63063ed..ad8b2a34ebceb 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/base_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/base_product.py @@ -33,6 +33,6 @@ class BaseProduct(Model): 'description': {'key': 'base_product_description', 'type': 'str'}, } - def __init__(self, product_id, description=None, **kwargs): + def __init__(self, product_id, description=None): self.product_id = product_id self.description = description diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/error.py index bb9d41eb9cbde..0ff39bf5de7f9 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/error.py @@ -31,7 +31,7 @@ class Error(Model): 'parent_error': {'key': 'parentError', 'type': 'Error'}, } - def __init__(self, status=None, message=None, parent_error=None, **kwargs): + def __init__(self, status=None, message=None, parent_error=None): self.status = status self.message = message self.parent_error = parent_error diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py index 5043aa2867c4e..ef30dd1f2d039 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flatten_parameter_group.py @@ -26,6 +26,8 @@ class FlattenParameterGroup(Model): :type description: str :param max_product_display_name: Display name of product. :type max_product_display_name: str + :param generic_value: Generic URL value. + :type generic_value: str :param odatavalue: URL value. :type odatavalue: str """ @@ -36,9 +38,10 @@ class FlattenParameterGroup(Model): 'max_product_display_name': {'required': True}, } - def __init__(self, name, product_id, max_product_display_name, description=None, odatavalue=None, **kwargs): + def __init__(self, name, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None): self.name = name self.product_id = product_id self.description = description self.max_product_display_name = max_product_display_name + self.generic_value = generic_value self.odatavalue = odatavalue diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py index 458eef6da4c3d..55df7eedae364 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/flattened_product.py @@ -15,28 +15,38 @@ class FlattenedProduct(Resource): """FlattenedProduct - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str :param pname: :type pname: str :param flattened_product_type: :type flattened_product_type: str - :param provisioning_state_values: Possible values include: 'Succeeded', + :ivar provisioning_state_values: Possible values include: 'Succeeded', 'Failed', 'canceled', 'Accepted', 'Creating', 'Created', 'Updating', 'Updated', 'Deleting', 'Deleted', 'OK' - :type provisioning_state_values: str + :vartype provisioning_state_values: str :param provisioning_state: :type provisioning_state: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + 'provisioning_state_values': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -49,9 +59,9 @@ class FlattenedProduct(Resource): 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, pname=None, flattened_product_type=None, provisioning_state_values=None, provisioning_state=None, **kwargs): - super(FlattenedProduct, self).__init__(id=id, type=type, tags=tags, location=location, name=name, **kwargs) + def __init__(self, tags=None, location=None, pname=None, flattened_product_type=None, provisioning_state=None): + super(FlattenedProduct, self).__init__(tags=tags, location=location) self.pname = pname self.flattened_product_type = flattened_product_type - self.provisioning_state_values = provisioning_state_values + self.provisioning_state_values = None self.provisioning_state = provisioning_state diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py new file mode 100644 index 0000000000000..44d207c724ad2 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/generic_url.py @@ -0,0 +1,28 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is +# regenerated. +# -------------------------------------------------------------------------- + +from msrest.serialization import Model + + +class GenericUrl(Model): + """ + The Generic URL. + + :param generic_value: Generic URL value. + :type generic_value: str + """ + + _attribute_map = { + 'generic_value': {'key': 'generic_value', 'type': 'str'}, + } + + def __init__(self, generic_value=None): + self.generic_value = generic_value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py index c2e81e8035ee3..349e6b7fbd717 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource.py @@ -15,18 +15,27 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param type: Resource Type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar type: Resource Type + :vartype type: str :param tags: :type tags: dict :param location: Resource Location :type location: str - :param name: Resource Name - :type name: str + :ivar name: Resource Name + :vartype name: str """ + _validation = { + 'id': {'readonly': True}, + 'type': {'readonly': True}, + 'name': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, @@ -35,9 +44,9 @@ class Resource(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, type=None, tags=None, location=None, name=None, **kwargs): - self.id = id - self.type = type + def __init__(self, tags=None, location=None): + self.id = None + self.type = None self.tags = tags self.location = location - self.name = name + self.name = None diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py index e84cbdeba5dea..b4c53e9e238ba 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/resource_collection.py @@ -31,7 +31,7 @@ class ResourceCollection(Model): 'dictionaryofresources': {'key': 'dictionaryofresources', 'type': '{FlattenedProduct}'}, } - def __init__(self, productresource=None, arrayofresources=None, dictionaryofresources=None, **kwargs): + def __init__(self, productresource=None, arrayofresources=None, dictionaryofresources=None): self.productresource = productresource self.arrayofresources = arrayofresources self.dictionaryofresources = dictionaryofresources diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py index 8cf7fdd16f4cd..02537d1797c79 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/autorestresourceflatteningtestservice/models/simple_product.py @@ -16,6 +16,9 @@ class SimpleProduct(BaseProduct): """ The product documentation. + Variables are only populated by the server, and will be ignored when + sending a request. + :param product_id: Unique identifier representing a specific product for a given latitude & longitude. For example, uberX in San Francisco will have a different product_id than uberX in Los Angeles. @@ -24,9 +27,11 @@ class SimpleProduct(BaseProduct): :type description: str :param max_product_display_name: Display name of product. :type max_product_display_name: str - :param capacity: Capacity of product. For example, 4 people. Default + :ivar capacity: Capacity of product. For example, 4 people. Default value: "Large" . - :type capacity: str + :vartype capacity: str + :param generic_value: Generic URL value. + :type generic_value: str :param odatavalue: URL value. :type odatavalue: str """ @@ -34,7 +39,7 @@ class SimpleProduct(BaseProduct): _validation = { 'product_id': {'required': True}, 'max_product_display_name': {'required': True}, - 'capacity': {'required': True}, + 'capacity': {'required': True, 'constant': True}, } _attribute_map = { @@ -42,11 +47,14 @@ class SimpleProduct(BaseProduct): 'description': {'key': 'base_product_description', 'type': 'str'}, 'max_product_display_name': {'key': 'details.max_product_display_name', 'type': 'str'}, 'capacity': {'key': 'details.max_product_capacity', 'type': 'str'}, + 'generic_value': {'key': 'details.max_product_image.generic_value', 'type': 'str'}, 'odatavalue': {'key': 'details.max_product_image.@odata\\.value', 'type': 'str'}, } - def __init__(self, product_id, max_product_display_name, description=None, odatavalue=None, **kwargs): - super(SimpleProduct, self).__init__(product_id=product_id, description=description, **kwargs) + capacity = "Large" + + def __init__(self, product_id, max_product_display_name, description=None, generic_value=None, odatavalue=None): + super(SimpleProduct, self).__init__(product_id=product_id, description=description) self.max_product_display_name = max_product_display_name - self.capacity = "Large" + self.generic_value = generic_value self.odatavalue = odatavalue diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/setup.py index 4eebe2a59088e..326c330b62a5b 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ModelFlattening/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/autorestparameterflattening/models/availability_set_update_parameters.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/autorestparameterflattening/models/availability_set_update_parameters.py index 7c14ba67a9fd0..eb0b7aa4d4e00 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/autorestparameterflattening/models/availability_set_update_parameters.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/autorestparameterflattening/models/availability_set_update_parameters.py @@ -27,5 +27,5 @@ class AvailabilitySetUpdateParameters(Model): 'tags': {'key': 'tags', 'type': '{str}'}, } - def __init__(self, tags, **kwargs): + def __init__(self, tags): self.tags = tags diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/setup.py index 81ec092249336..1e6900d3ef817 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/ParameterFlattening/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/autorestreportservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/autorestreportservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/autorestreportservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/autorestreportservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/setup.py index c1ba503f44a53..ff3a17c58c7ff 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Report/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py index d9a36a8ffd5b0..7dcce131d92ad 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/auto_rest_required_optional_test_service.py @@ -36,9 +36,13 @@ def __init__( self, required_global_path, required_global_query, optional_global_query=None, base_url=None, filepath=None): if required_global_path is None: - raise ValueError('required_global_path must not be None.') + raise ValueError("Parameter 'required_global_path' must not be None.") + if not isinstance(required_global_path, str): + raise TypeError("Parameter 'required_global_path' must be str.") if required_global_query is None: - raise ValueError('required_global_query must not be None.') + raise ValueError("Parameter 'required_global_query' must not be None.") + if not isinstance(required_global_query, str): + raise TypeError("Parameter 'required_global_query' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_optional_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_optional_wrapper.py index b5c3efad06a28..cb71ed5d5debe 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_optional_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_optional_wrapper.py @@ -23,5 +23,5 @@ class ArrayOptionalWrapper(Model): 'value': {'key': 'value', 'type': '[str]'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_wrapper.py index 7eb7270bfd325..43685d1c6dba2 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/array_wrapper.py @@ -27,5 +27,5 @@ class ArrayWrapper(Model): 'value': {'key': 'value', 'type': '[str]'}, } - def __init__(self, value, **kwargs): + def __init__(self, value): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_optional_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_optional_wrapper.py index 269a6f0c146a3..4d0d010de7de7 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_optional_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_optional_wrapper.py @@ -24,5 +24,5 @@ class ClassOptionalWrapper(Model): 'value': {'key': 'value', 'type': 'Product'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_wrapper.py index 9e9278497aaf4..ff139aaf09fd4 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/class_wrapper.py @@ -28,5 +28,5 @@ class ClassWrapper(Model): 'value': {'key': 'value', 'type': 'Product'}, } - def __init__(self, value, **kwargs): + def __init__(self, value): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_optional_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_optional_wrapper.py index ec49c66263db1..366aa950c993d 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_optional_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_optional_wrapper.py @@ -23,5 +23,5 @@ class IntOptionalWrapper(Model): 'value': {'key': 'value', 'type': 'int'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_wrapper.py index 558b905ae14b7..9d20dbc5fba7a 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/int_wrapper.py @@ -27,5 +27,5 @@ class IntWrapper(Model): 'value': {'key': 'value', 'type': 'int'}, } - def __init__(self, value, **kwargs): + def __init__(self, value): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/product.py index 438c0c95e8f11..68be843067783 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/product.py @@ -30,6 +30,6 @@ class Product(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id, name=None, **kwargs): + def __init__(self, id, name=None): self.id = id self.name = name diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_optional_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_optional_wrapper.py index 70f024163a822..b7484c342146e 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_optional_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_optional_wrapper.py @@ -23,5 +23,5 @@ class StringOptionalWrapper(Model): 'value': {'key': 'value', 'type': 'str'}, } - def __init__(self, value=None, **kwargs): + def __init__(self, value=None): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_wrapper.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_wrapper.py index 8494e03473016..659da492dd4f5 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_wrapper.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/autorestrequiredoptionaltestservice/models/string_wrapper.py @@ -27,5 +27,5 @@ class StringWrapper(Model): 'value': {'key': 'value', 'type': 'str'}, } - def __init__(self, value, **kwargs): + def __init__(self, value): self.value = value diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/setup.py index aa49668c0f66d..14f66afcfb516 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/RequiredOptional/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py index 31c1880929875..34efde192fd6b 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/auto_rest_url_test_service.py @@ -36,7 +36,11 @@ def __init__( self, global_string_path, global_string_query=None, base_url=None, filepath=None): if global_string_path is None: - raise ValueError('global_string_path must not be None.') + raise ValueError("Parameter 'global_string_path' must not be None.") + if not isinstance(global_string_path, str): + raise TypeError("Parameter 'global_string_path' must be str.") + if global_string_query is not None and not isinstance(global_string_query, str): + raise TypeError("Optional parameter 'global_string_query' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/models/error.py index b8957d8dfa0cc..c2d19e377e004 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/models/error.py @@ -27,7 +27,7 @@ class Error(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, status=None, message=None, **kwargs): + def __init__(self, status=None, message=None): self.status = status self.message = message diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py index b8f8b973a26b6..97cd8878c0e6a 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py @@ -1026,3 +1026,91 @@ def date_time_null( if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response + + def base64_url( + self, base64_url_path, custom_headers={}, raw=False, **operation_config): + """ + Get 'lorem' encoded value as 'bG9yZW0' (base64url) + + :param base64_url_path: base64url encoded value + :type base64_url_path: str + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: None + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/paths/string/bG9yZW0/{base64UrlPath}' + path_format_arguments = { + 'base64UrlPath': self._serialize.url("base64_url_path", base64_url_path, 'str') + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + if raw: + client_raw_response = ClientRawResponse(None, response) + return client_raw_response + + def array_csv_in_path( + self, array_path, custom_headers={}, raw=False, **operation_config): + """ + Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , + null, ''] using the csv-array format + + :param array_path: an array of string ['ArrayPath1', 'begin!*'();:@ + &=+$,/?#[]end' , null, ''] using the csv-array format + :type array_path: list of str + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :param operation_config: :ref:`Operation configuration + overrides`. + :rtype: None + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath}' + path_format_arguments = { + 'arrayPath': self._serialize.url("array_path", array_path, '[str]', div=',') + } + url = self._client.format_url(url, **path_format_arguments) + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if custom_headers: + header_parameters.update(custom_headers) + + # Construct and send request + request = self._client.get(url, query_parameters) + response = self._client.send(request, header_parameters, **operation_config) + + if response.status_code not in [200]: + raise models.ErrorException(self._deserialize, response) + + if raw: + client_raw_response = ClientRawResponse(None, response) + return client_raw_response diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/setup.py index 5db4f0ba4406a..5ecd97fb73461 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py index 7fd4093d00b6e..f9a6b88ede469 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/auto_rest_validation_test.py @@ -34,9 +34,13 @@ def __init__( self, subscription_id, api_version, base_url=None, filepath=None): if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") if api_version is None: - raise ValueError('api_version must not be None.') + raise ValueError("Parameter 'api_version' must not be None.") + if not isinstance(api_version, str): + raise TypeError("Parameter 'api_version' must be str.") if not base_url: base_url = 'http://localhost' diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py index 9c02450e6e110..0ef944dd8e9ca 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/child_product.py @@ -16,14 +16,17 @@ class ChildProduct(Model): """ The product documentation. - :param const_property: Constant string. Default value: "constant" . - :type const_property: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar const_property: Constant string. Default value: "constant" . + :vartype const_property: str :param count: Count :type count: int """ _validation = { - 'const_property': {'required': True}, + 'const_property': {'required': True, 'constant': True}, } _attribute_map = { @@ -31,6 +34,7 @@ class ChildProduct(Model): 'count': {'key': 'count', 'type': 'int'}, } - def __init__(self, count=None, **kwargs): - self.const_property = "constant" + const_property = "constant" + + def __init__(self, count=None): self.count = count diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py index 98f60fd2eab82..cb4531c4ec1aa 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/constant_product.py @@ -16,15 +16,18 @@ class ConstantProduct(Model): """ The product documentation. - :param const_property: Constant string. Default value: "constant" . - :type const_property: str - :param const_property2: Constant string2. Default value: "constant2" . - :type const_property2: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar const_property: Constant string. Default value: "constant" . + :vartype const_property: str + :ivar const_property2: Constant string2. Default value: "constant2" . + :vartype const_property2: str """ _validation = { - 'const_property': {'required': True}, - 'const_property2': {'required': True}, + 'const_property': {'required': True, 'constant': True}, + 'const_property2': {'required': True, 'constant': True}, } _attribute_map = { @@ -32,6 +35,6 @@ class ConstantProduct(Model): 'const_property2': {'key': 'constProperty2', 'type': 'str'}, } - def __init__(self, **kwargs): - self.const_property = "constant" - self.const_property2 = "constant2" + const_property = "constant" + + const_property2 = "constant2" diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/error.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/error.py index 7284a2e86309f..3cd8f0d632c08 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/error.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/error.py @@ -30,7 +30,7 @@ class Error(Model): 'fields': {'key': 'fields', 'type': 'str'}, } - def __init__(self, code=None, message=None, fields=None, **kwargs): + def __init__(self, code=None, message=None, fields=None): self.code = code self.message = message self.fields = fields diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py index 0447d1ff7f400..65d49c5d12e17 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/autorestvalidationtest/models/product.py @@ -9,6 +9,7 @@ # regenerated. # -------------------------------------------------------------------------- +from .constant_product import ConstantProduct from msrest.serialization import Model @@ -16,6 +17,9 @@ class Product(Model): """ The product documentation. + Variables are only populated by the server, and will be ignored when + sending a request. + :param display_names: Non required array of unique items from 0 to 6 elements. :type display_names: list of str @@ -26,13 +30,13 @@ class Product(Model): :param child: :type child: :class:`ChildProduct ` - :param const_child: - :type const_child: :class:`ConstantProduct + :ivar const_child: + :vartype const_child: :class:`ConstantProduct ` - :param const_int: Constant int. Default value: 0 . - :type const_int: int - :param const_string: Constant string. Default value: "constant" . - :type const_string: str + :ivar const_int: Constant int. Default value: 0 . + :vartype const_int: int + :ivar const_string: Constant string. Default value: "constant" . + :vartype const_string: str :param const_string_as_enum: Constant string as Enum. Possible values include: 'constant_string_as_enum' :type const_string_as_enum: str @@ -43,9 +47,9 @@ class Product(Model): 'capacity': {'maximum_ex': 100, 'minimum_ex': 0}, 'image': {'pattern': 'http://\w+'}, 'child': {'required': True}, - 'const_child': {'required': True}, - 'const_int': {'required': True}, - 'const_string': {'required': True}, + 'const_child': {'required': True, 'constant': True}, + 'const_int': {'required': True, 'constant': True}, + 'const_string': {'required': True, 'constant': True}, } _attribute_map = { @@ -59,12 +63,15 @@ class Product(Model): 'const_string_as_enum': {'key': 'constStringAsEnum', 'type': 'EnumConst'}, } - def __init__(self, child, display_names=None, capacity=None, image=None, const_string_as_enum=None, **kwargs): + const_child = ConstantProduct() + + const_int = 0 + + const_string = "constant" + + def __init__(self, child, display_names=None, capacity=None, image=None, const_string_as_enum=None): self.display_names = display_names self.capacity = capacity self.image = image self.child = child - self.const_child = None - self.const_int = 0 - self.const_string = "constant" self.const_string_as_enum = const_string_as_enum diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/setup.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/setup.py index 22a1da7feac0a..3d693bfbb149f 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/setup.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Validation/setup.py @@ -22,7 +22,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/AutoRest/Generators/Python/Python.Tests/Python.Tests.pyproj b/AutoRest/Generators/Python/Python.Tests/Python.Tests.pyproj index 551692fe3e198..b6cfb6ea96c3e 100644 --- a/AutoRest/Generators/Python/Python.Tests/Python.Tests.pyproj +++ b/AutoRest/Generators/Python/Python.Tests/Python.Tests.pyproj @@ -125,6 +125,10 @@ + + + + diff --git a/AutoRest/Generators/Python/Python/PythonCodeGenerator.cs b/AutoRest/Generators/Python/Python/PythonCodeGenerator.cs index ff332c771c70e..d987055d49f6f 100644 --- a/AutoRest/Generators/Python/Python/PythonCodeGenerator.cs +++ b/AutoRest/Generators/Python/Python/PythonCodeGenerator.cs @@ -16,7 +16,7 @@ namespace Microsoft.Rest.Generator.Python { public class PythonCodeGenerator : CodeGenerator { - private const string ClientRuntimePackage = "msrest version 0.1.0"; + private const string ClientRuntimePackage = "msrest version 0.2.0"; public PythonCodeGenerator(Settings settings) : base(settings) { diff --git a/AutoRest/Generators/Python/Python/PythonCodeNamer.cs b/AutoRest/Generators/Python/Python/PythonCodeNamer.cs index 779c4ebd70120..11ae0801acce4 100644 --- a/AutoRest/Generators/Python/Python/PythonCodeNamer.cs +++ b/AutoRest/Generators/Python/Python/PythonCodeNamer.cs @@ -324,7 +324,11 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) throw new ArgumentNullException("primaryType"); } - if (primaryType.Type == KnownPrimaryType.Boolean) + if (primaryType.Type == KnownPrimaryType.Base64Url) + { + primaryType.Name = "str"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) { primaryType.Name = "bool"; } @@ -372,6 +376,10 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) { primaryType.Name = "Decimal"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + primaryType.Name = "long"; + } else if (primaryType.Type == KnownPrimaryType.Object) // Revisit here { primaryType.Name = "object"; diff --git a/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs index 5c47e7be1f83c..ee71dc5b08b4d 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/MethodTemplateModel.cs @@ -6,6 +6,7 @@ using System.Globalization; using System.Linq; using System.Net; +using System.Text.RegularExpressions; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Python.TemplateModels; using Microsoft.Rest.Generator.Utilities; @@ -31,6 +32,19 @@ public MethodTemplateModel(Method source, ServiceClient serviceClient) OperationName = serviceClient.Name; } AddCustomHeader = true; + string formatter; + foreach (var parameter in LocalParameters) + { + if (string.IsNullOrWhiteSpace(parameter.DefaultValue)) + { + parameter.DefaultValue = PythonConstants.None; + } + } + foreach (Match m in Regex.Matches(Url, @"\{[\w]+:[\w]+\}")) + { + formatter = m.Value.Split(':').First() + '}'; + Url = Url.Replace(m.Value, formatter); + } } public bool AddCustomHeader { get; private set; } @@ -151,7 +165,7 @@ public virtual string MethodParameterDeclaration(bool addCustomHeaderParameters) foreach (var parameter in LocalParameters) { - if (parameter.IsRequired && parameter.DefaultValue.Equals(PythonConstants.None)) + if (parameter.IsRequired && parameter.DefaultValue == PythonConstants.None) { requiredDeclarations.Add(parameter.Name); } diff --git a/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs index c63acff125dfc..2c43e7c092ca7 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/ModelTemplateModel.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Globalization; using System.Linq; +using System.Text; using Microsoft.Rest.Generator.ClientModel; using Microsoft.Rest.Generator.Python.TemplateModels; using Microsoft.Rest.Generator.Utilities; @@ -48,6 +49,14 @@ public ModelTemplateModel(CompositeType source, ServiceClient serviceClient) _parent = new ModelTemplateModel(source.BaseModelType, serviceClient); } + foreach (var property in ComposedProperties) + { + if (string.IsNullOrWhiteSpace(property.DefaultValue)) + { + property.DefaultValue = PythonConstants.None; + } + } + if (this.IsPolymorphic) { foreach (var modelType in ServiceClient.ModelTypes) @@ -100,6 +109,14 @@ public IList Validators { validation.Add("'required': True"); } + if (parameter.IsConstant) + { + validation.Add("'constant': True"); + } + if (parameter.IsReadOnly) + { + validation.Add("'readonly': True"); + } if (parameter.Constraints.Any()) { validation.AddRange(BuildValidationParameters(parameter.Constraints)); @@ -186,6 +203,22 @@ public bool HasParent get { return this._parent != null; } } + public bool NeedsConstructor + { + get + { + var nonConstant = Properties.Where(p => !p.IsConstant); + if (nonConstant.Any()) + { + return true; + } + else + { + return (HasParent || NeedsPolymorphicConverter); + } + } + } + /// /// Provides the modelProperty documentation string along with default value if any. /// @@ -198,11 +231,14 @@ public static string GetPropertyDocumentationString(Property property) { throw new ArgumentNullException("property"); } - string docString = string.Format(CultureInfo.InvariantCulture, ":param {0}:", property.Name); - + if (property.IsConstant || property.IsReadOnly) + { + docString = string.Format(CultureInfo.InvariantCulture, ":ivar {0}:", property.Name); + } + string documentation = property.Documentation; - if (!string.IsNullOrWhiteSpace(property.DefaultValue) && property.DefaultValue != PythonConstants.None) + if (property.DefaultValue != PythonConstants.None) { if (documentation != null && !documentation.EndsWith(".", StringComparison.OrdinalIgnoreCase)) { @@ -239,16 +275,43 @@ public IList RequiredFieldsList } } + public IEnumerable ReadOnlyAttributes + { + get + { + return ComposedProperties.Where(p => p.IsConstant || p.IsReadOnly); + } + } + + public IDictionary ComplexConstants + { + get + { + Dictionary complexConstant = new Dictionary (); + foreach (var property in Properties) + { + if (property.IsConstant) + { + CompositeType compType = property.Type as CompositeType; + if (compType != null) + { + complexConstant[property.Name] = compType; + } + } + } + return complexConstant; + } + } + public virtual string SuperParameterDeclaration() { List combinedDeclarations = new List(); - foreach (var property in ComposedProperties.Except(Properties)) + foreach (var property in ComposedProperties.Except(Properties).Except(ReadOnlyAttributes)) { if (this.IsPolymorphic) if (property.Name == this.BasePolymorphicDiscriminator) continue; - combinedDeclarations.Add(string.Format(CultureInfo.InvariantCulture, "{0}={0}", property.Name)); } return string.Join(", ", combinedDeclarations); @@ -260,17 +323,13 @@ public virtual string MethodParameterDeclaration() List requiredDeclarations = new List(); List combinedDeclarations = new List(); - foreach (var property in ComposedProperties) + foreach (var property in ComposedProperties.Except(ReadOnlyAttributes)) { if (this.IsPolymorphic) if (property.Name == this.BasePolymorphicDiscriminator) continue; - if (property.IsConstant) - { - continue; - } - if (property.IsRequired && property.DefaultValue.Equals(PythonConstants.None)) + if (property.IsRequired && property.DefaultValue == PythonConstants.None) { requiredDeclarations.Add(property.Name); } @@ -359,9 +418,20 @@ public string InitializeProperty(string objectName, Property property) { throw new ArgumentNullException("property"); } + if (property.IsReadOnly) + { + return string.Format(CultureInfo.InvariantCulture, "{0}.{1} = None", objectName, property.Name); + } if (property.IsConstant) { - return string.Format(CultureInfo.InvariantCulture, "{0}.{1} = {2}", objectName, property.Name, property.DefaultValue); + if (ComplexConstants.ContainsKey(property.Name)) + { + return string.Format(CultureInfo.InvariantCulture, "{0} = {1}()", property.Name, property.Type.Name); + } + else + { + return string.Format(CultureInfo.InvariantCulture, "{0} = {1}", property.Name, property.DefaultValue); + } } if (IsPolymorphic) { diff --git a/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs b/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs index 3e9d595d83f47..60629ea26ca28 100644 --- a/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs +++ b/AutoRest/Generators/Python/Python/TemplateModels/ServiceClientTemplateModel.cs @@ -105,7 +105,10 @@ public virtual string RequiredConstructorParameters } } - [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ValueError"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "ValueError"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "TypeError"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "str"), + System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "Microsoft.Rest.Generator.Utilities.IndentedStringBuilder.AppendLine(System.String)")] public virtual string ValidateRequiredParameters { get @@ -118,9 +121,31 @@ public virtual string ValidateRequiredParameters builder. AppendFormat("if {0} is None:", property.Name.ToPythonCase()).AppendLine(). Indent(). - AppendLine(string.Format(CultureInfo.InvariantCulture, "raise ValueError('{0} must not be None.')", property.Name.ToPythonCase())). + AppendLine(string.Format(CultureInfo.InvariantCulture, "raise ValueError(\"Parameter '{0}' must not be None.\")", property.Name.ToPythonCase())). Outdent(); + if (property.Type.IsPrimaryType(KnownPrimaryType.String)) + { + builder. + AppendFormat("if not isinstance({0}, str):", property.Name.ToPythonCase()).AppendLine(). + Indent(). + AppendLine(string.Format(CultureInfo.InvariantCulture, "raise TypeError(\"Parameter '{0}' must be str.\")", property.Name.ToPythonCase())). + Outdent(); + } } + else + { + if (property.Type.IsPrimaryType(KnownPrimaryType.String)) + { + builder. + AppendFormat("if {0} is not None and not isinstance({0}, str):", property.Name.ToPythonCase()).AppendLine(). + Indent(). + AppendLine(string.Format(CultureInfo.InvariantCulture, "raise TypeError(\"Optional parameter '{0}' must be str.\")", property.Name.ToPythonCase())). + Outdent(); + } + + } + + } return builder.ToString(); } @@ -138,7 +163,7 @@ public virtual string SetupRequires { get { - return "\"msrest>=0.1.0\""; + return "\"msrest>=0.2.0\""; } } diff --git a/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml b/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml index d035a46155cf1..17e86079f9cfd 100644 --- a/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml +++ b/AutoRest/Generators/Python/Python/Templates/ModelTemplate.cshtml @@ -11,6 +11,13 @@ @Header("# ").TrimMultilineHeader() # -------------------------------------------------------------------------- @EmptyLine +@if(Model.ComplexConstants.Any()) +{ + foreach(var property in Model.ComplexConstants.Values) + { +@:from .@property.Name.ToPythonCase() import @property.Name + } +} @if (Model.BaseModelType != null) { @:from .@Model.BaseModelType.Name.ToPythonCase() import @Model.BaseModelType.Name @@ -42,14 +49,26 @@ else { @: """@(Model.Name) } +@if (Model.ReadOnlyAttributes.Any()) +{ +@EmptyLine +@: @WrapComment(string.Empty, "Variables are only populated by the server, and will be ignored when sending a request.") +} @if (Model.ComposedProperties.Any()) { @EmptyLine - foreach (var property in Model.ComposedProperties) - { + foreach (var property in Model.ComposedProperties) + { @: @ParameterWrapComment(string.Empty, ModelTemplateModel.GetPropertyDocumentationString(property)) + if (property.IsConstant || property.IsReadOnly) + { +@: @ParameterWrapComment(string.Empty, ":vartype " + property.Name + ": " + Model.GetPropertyDocumentationType(property.Type)) + } + else + { @: @ParameterWrapComment(string.Empty, ":type " + property.Name + ": " + Model.GetPropertyDocumentationType(property.Type)) - } + } + } } """ @if (Model.Validators.Any() || Model.RequiredFieldsList.Any()) @@ -89,26 +108,37 @@ else } } -@EmptyLine - def __init__(self@(Model.MethodParameterDeclaration()), **kwargs): -@if (Model.HasParent) +@foreach(var property in Model.Properties) { - @:super(@(Model.Name), self).__init__(@(Model.SuperParameterDeclaration()), **kwargs) + if (property.IsConstant) + { +@EmptyLine + @:@(Model.InitializeProperty(String.Empty, property)) + } } -@{ - var propertyList = new List(Model.Properties); - if (propertyList.Count > 0) - { - for (int i = 0; i < propertyList.Count; i++) - { +@if (Model.NeedsConstructor) +{ +@EmptyLine + @:def __init__(self@(Model.MethodParameterDeclaration())): + if (Model.HasParent) + { + @:super(@(Model.Name), self).__init__(@(Model.SuperParameterDeclaration())) + } + var propertyList = new List(Model.Properties); + if (propertyList.Count > 0) + { + for (int i = 0; i < propertyList.Count; i++) + { + if (!propertyList[i].IsConstant) + { @:@(Model.InitializeProperty("self", propertyList[i])) - } + } + } } -} - -@if (Model.NeedsPolymorphicConverter) -{ + if (Model.NeedsPolymorphicConverter) + { @:self.@Model.BasePolymorphicDiscriminator = '@Model.SerializedName' + } } @if (Model.IsException) { diff --git a/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs b/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs index 70579ad6c3a99..c40423ee1b4ae 100644 --- a/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs +++ b/AutoRest/Generators/Ruby/Ruby/RubyCodeNamer.cs @@ -323,7 +323,11 @@ private IType NormalizePrimaryType(PrimaryType primaryType) throw new ArgumentNullException("primaryType"); } - if (primaryType.Type == KnownPrimaryType.Boolean) + if (primaryType.Type == KnownPrimaryType.Base64Url) + { + primaryType.Name = "String"; + } + else if (primaryType.Type == KnownPrimaryType.Boolean) { primaryType.Name = "Boolean"; } @@ -368,6 +372,10 @@ private IType NormalizePrimaryType(PrimaryType primaryType) { primaryType.Name = "Duration"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + primaryType.Name = "Bignum"; + } else if (primaryType.Type == KnownPrimaryType.Object) { primaryType.Name = "Object"; diff --git a/AutoRest/Generators/Ruby/Ruby/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Ruby/Ruby/TemplateModels/MethodTemplateModel.cs index 405533fd14139..f66881e9294be 100644 --- a/AutoRest/Generators/Ruby/Ruby/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Ruby/Ruby/TemplateModels/MethodTemplateModel.cs @@ -280,7 +280,7 @@ public virtual string CreateSerializationString(string inputVariable, IType type builder.AppendLine(serializationLogic); // After that - generate JSON object after serializing each component. - return builder.AppendLine("{0} = JSON.generate({1}, quirks_mode: true)", outputVariable, inputVariable).ToString(); + return builder.AppendLine("{0} = {1} != nil ? JSON.generate({1}, quirks_mode: true) : nil", outputVariable, inputVariable).ToString(); } /// diff --git a/AutoRest/Modelers/Swagger.Tests/Swagger/swagger-data-types.json b/AutoRest/Modelers/Swagger.Tests/Swagger/swagger-data-types.json index afec02a0266f4..4e7e1da3f3084 100644 --- a/AutoRest/Modelers/Swagger.Tests/Swagger/swagger-data-types.json +++ b/AutoRest/Modelers/Swagger.Tests/Swagger/swagger-data-types.json @@ -13,7 +13,7 @@ "produces": [ "application/json" ], "consumes": [ "application/json" ], "paths": { - "/subscriptions/{integer}/{int}/{long}/{number}/{float}/{double}/{string}/{enum}/{byte}/{boolean}/{date}/{dateTime}?invalues='{array}'": { + "/subscriptions/{integer}/{int}/{long}/{number}/{float}/{double}/{string}/{enum}/{byte}/{boolean}/{date}/{dateTime}/{base64url}?invalues='{array}'": { "get": { "operationId": "list", "summary": "Product Types", @@ -93,6 +93,12 @@ "type": "string", "format": "date-time" }, + { + "name": "base64url", + "in": "path", + "type": "string", + "format": "base64url" + }, { "name": "array", "in": "query", diff --git a/AutoRest/Modelers/Swagger.Tests/SwaggerModelerTests.cs b/AutoRest/Modelers/Swagger.Tests/SwaggerModelerTests.cs index 3e6043847f7a0..0aac57a71e45f 100644 --- a/AutoRest/Modelers/Swagger.Tests/SwaggerModelerTests.cs +++ b/AutoRest/Modelers/Swagger.Tests/SwaggerModelerTests.cs @@ -347,7 +347,8 @@ public void TestDataTypes() Assert.Equal("Boolean boolean", clientModel.Methods[0].Parameters[10].ToString()); Assert.Equal("Date date", clientModel.Methods[0].Parameters[11].ToString()); Assert.Equal("DateTime dateTime", clientModel.Methods[0].Parameters[12].ToString()); - Assert.Equal("IList array", clientModel.Methods[0].Parameters[13].ToString()); + Assert.Equal("Base64Url base64url", clientModel.Methods[0].Parameters[13].ToString()); + Assert.Equal("IList array", clientModel.Methods[0].Parameters[14].ToString()); var variableEnumInPath = clientModel.Methods.First(m => m.Name == "list" && m.Group == null).Parameters.First(p => p.Name == "color" && p.Location == ParameterLocation.Path).Type as EnumType; diff --git a/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs b/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs index edfba8a2c1340..f9ee08f3c57f6 100644 --- a/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs +++ b/AutoRest/Modelers/Swagger/CollectionFormatBuilder.cs @@ -80,7 +80,7 @@ private static void AddCollectionFormat(SwaggerParameter swaggerParameter, Strin break; case CollectionFormat.Multi: - // TODO multi is not supported yet: http://vstfrd:8080/Azure/RD/_workitems/edit/3172867 + // TODO multi is not supported yet: https://github.com/Azure/autorest/issues/717 throw new NotSupportedException(string.Format(CultureInfo.InvariantCulture, Resources.MultiCollectionFormatNotSupported, swaggerParameter.Name)); diff --git a/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs b/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs index 29b7e35a11275..02bfb0d23b8bc 100644 --- a/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs +++ b/AutoRest/Modelers/Swagger/Model/SwaggerObject.cs @@ -116,6 +116,10 @@ public PrimaryType ToType() { return new PrimaryType(KnownPrimaryType.Uuid); } + if (string.Equals("base64url", Format, StringComparison.OrdinalIgnoreCase)) + { + return new PrimaryType(KnownPrimaryType.Base64Url); + } return new PrimaryType(KnownPrimaryType.String); case DataType.Number: if (string.Equals("decimal", Format, StringComparison.OrdinalIgnoreCase)) @@ -128,6 +132,10 @@ public PrimaryType ToType() { return new PrimaryType(KnownPrimaryType.Long); } + if (string.Equals("unixtime", Format, StringComparison.OrdinalIgnoreCase)) + { + return new PrimaryType(KnownPrimaryType.UnixTime); + } return new PrimaryType(KnownPrimaryType.Int); case DataType.Boolean: return new PrimaryType(KnownPrimaryType.Boolean); diff --git a/AutoRest/NugetPackageTest/NugetPackageCSharpTest.csproj b/AutoRest/NugetPackageTest/NugetPackageCSharpTest.csproj index ac46023f2570a..b2e0451a3fb47 100644 --- a/AutoRest/NugetPackageTest/NugetPackageCSharpTest.csproj +++ b/AutoRest/NugetPackageTest/NugetPackageCSharpTest.csproj @@ -39,7 +39,7 @@ - packages\Microsoft.Rest.ClientRuntime.2.1.0\lib\net45\Microsoft.Rest.ClientRuntime.dll + packages\Microsoft.Rest.ClientRuntime.2.2.0\lib\net45\Microsoft.Rest.ClientRuntime.dll True diff --git a/AutoRest/NugetPackageTest/packages.config b/AutoRest/NugetPackageTest/packages.config index 38ea62de43340..356cf06d88364 100644 --- a/AutoRest/NugetPackageTest/packages.config +++ b/AutoRest/NugetPackageTest/packages.config @@ -1,6 +1,6 @@ - + diff --git a/AutoRest/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index 4d8d3d47144d1..9453e73965c22 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -113,7 +113,7 @@ var coverage = { "getArrayComplexValid": 0, "putArrayComplexValid": 0, "getArrayDictionaryNull": 0, - "getArrayDictionaryEmpty": 0, + "getArrayDictionaryEmpty": 0, "getArrayDictionaryItemNull": 0, "getArrayDictionaryItemEmpty": 0, "getArrayDictionaryValid": 0, @@ -419,6 +419,8 @@ var coverage = { "ConstantsInPath": 0, "ConstantsInBody": 0, "CustomBaseUri": 0, + //Once all the languages implement this test, the scenario counter should be reset to zero. It is currently implemented in C# and node.js + "CustomBaseUriMoreOptions": 1, 'getModelFlattenArray': 0, 'putModelFlattenArray': 0, 'getModelFlattenDictionary': 0, @@ -427,7 +429,22 @@ var coverage = { 'putModelFlattenResourceCollection': 0, 'putModelFlattenCustomBase': 0, 'postModelFlattenCustomParameter': 0, - 'putModelFlattenCustomGroupedParameter': 0 + 'putModelFlattenCustomGroupedParameter': 0, + /* TODO: only C# and node.js support the base64url format currently. Exclude these tests from code coverage until it is implemented in other languages */ + "getStringBase64Encoded": 1, + "getStringBase64UrlEncoded": 1, + "putStringBase64UrlEncoded": 1, + "getStringNullBase64UrlEncoding": 1, + "getArrayBase64Url": 1, + "getDictionaryBase64Url": 1, + "UrlPathsStringBase64Url": 1, + "UrlPathsArrayCSVInPath": 1, + /* TODO: only C# supports the unixtime format currently. Exclude these tests from code coverage until it is implemented in other languages */ + "getUnixTime": 1, + "getInvalidUnixTime": 1, + "getNullUnixTime": 1, + "putUnixTime": 1, + "UrlPathsIntUnixTime": 1 }; // view engine setup diff --git a/AutoRest/TestServer/server/routes/array.js b/AutoRest/TestServer/server/routes/array.js index ca02fa94ecd6e..96bfc6217b924 100644 --- a/AutoRest/TestServer/server/routes/array.js +++ b/AutoRest/TestServer/server/routes/array.js @@ -177,8 +177,15 @@ var array = function (coverage) { } else { res.status(400).send('Request scenario for byte primitive type must contain valid or invalidnull'); } + } else if (req.params.type == 'base64url') { + if (req.params.scenario === 'valid') { + coverage['getArrayBase64Url']++; + res.status(200).end('[\"YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw\", \"dGVzdCBzdHJpbmc\", \"TG9yZW0gaXBzdW0\"]'); + } else { + res.status(400).send('Request scenario for base64url type must contain valid'); + } } else { - res.status(400).send('Request path must contain boolean or integer or float or double or string or date or date-time or byte'); + res.status(400).send('Request path must contain boolean or integer or float or double or string or date or date-time or byte or base64url'); } }); diff --git a/AutoRest/TestServer/server/routes/customUri.js b/AutoRest/TestServer/server/routes/customUri.js index 2eee79cadfc33..85d074cdeceb2 100644 --- a/AutoRest/TestServer/server/routes/customUri.js +++ b/AutoRest/TestServer/server/routes/customUri.js @@ -9,6 +9,17 @@ var specials = function (coverage) { coverage['CustomBaseUri']++; res.status(200).end(); }); + + router.get('/:subscriptionId/:keyName', function (req, res, next) { + if (req.params.subscriptionId === 'test12' && req.params.keyName === 'key1' + && Object.keys(req.query).length == 1 && req.query.keyVersion === 'v1') { + coverage['CustomBaseUriMoreOptions']++; + res.status(200).end(); + } else { + utils.send400(res, next, 'Either one of the path parameters (subscriptionId=test12, keyName=key1) or query parameter (keyVersion=v1) did not match. ' + + 'Received parameters are: subscriptionId ' + subscriptionId + ', keyName ' + keyName + ', keyVersion ' + keyVersion); + } + }); } specials.prototype.router = router; diff --git a/AutoRest/TestServer/server/routes/dictionary.js b/AutoRest/TestServer/server/routes/dictionary.js index f9b9a50635021..53a47c79d6fad 100644 --- a/AutoRest/TestServer/server/routes/dictionary.js +++ b/AutoRest/TestServer/server/routes/dictionary.js @@ -176,8 +176,15 @@ var dictionary = function(coverage) { } else { res.status(400).send('Request scenario for byte primitive type must contain valid or invalidnull'); } + } else if (req.params.type == 'base64url') { + if (req.params.scenario === 'valid') { + coverage['getDictionaryBase64Url']++; + res.status(200).end('{"0": "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw", "1": "dGVzdCBzdHJpbmc", "2": "TG9yZW0gaXBzdW0"}'); + } else { + res.status(400).send('Request scenario for base64url type must contain valid'); + } } else { - res.status(400).send('Request path must contain boolean or integer or float or double or string or date or date-time or byte'); + res.status(400).send('Request path must contain boolean or integer or float or double or string or date or date-time or byte or base64url'); } }); diff --git a/AutoRest/TestServer/server/routes/int.js b/AutoRest/TestServer/server/routes/int.js index 2299732ca5ad1..f4acbd7104cd2 100644 --- a/AutoRest/TestServer/server/routes/int.js +++ b/AutoRest/TestServer/server/routes/int.js @@ -65,10 +65,27 @@ var integer = function(coverage) { } else if (req.params.scenario === 'underflowint64') { coverage['getLongUnderflow']++; res.status(200).end('-9223372036854775910'); + } else if (req.params.scenario === 'unixtime') { + coverage['getUnixTime']++; + res.status(200).end('1460505600'); + } else if (req.params.scenario === 'invalidunixtime') { + coverage['getInvalidUnixTime']++; + res.status(200).end('123jkl'); + } else if (req.params.scenario === 'nullunixtime') { + coverage['getNullUnixTime']++; + res.status(200).end(); } else { res.status(400).send('Request path must contain true or false'); } - + }); + + router.put('/unixtime', function(req, res, next) { + if (req.body != 1460505600) { + utils.send400(res, next, "Did not like the value provided for unixtime in the req " + util.inspect(req.body)); + } else { + coverage['putUnixTime']++; + res.status(200).end(); + } }); } diff --git a/AutoRest/TestServer/server/routes/lros.js b/AutoRest/TestServer/server/routes/lros.js index 9d9dc540e16aa..ca11fa50082be 100644 --- a/AutoRest/TestServer/server/routes/lros.js +++ b/AutoRest/TestServer/server/routes/lros.js @@ -940,6 +940,17 @@ var lros = function (coverage) { res.status(400).end('{ "message" : "Error from the server" }'); }); + /* TODO: only C# has implemented this test. Exclude it from code coverage until it is implemented in other languages */ + coverage['LRONonRetryPut201Creating400InvalidJson'] = 1; + router.put('/nonretryerror/put/201/creating/400/invalidjson', function (req, res, next) { + res.status(201).end('{ "properties": { "provisioningState": "Creating"}, "id": "100", "name": "foo" }'); + }); + + router.get('/nonretryerror/put/201/creating/400/invalidjson', function (req, res, next) { + coverage['LRONonRetryPut201Creating400InvalidJson']++; + res.status(400).end('<{ "message" : "Error from the server" }'); + }); + coverage['LRONonRetryPutAsyncRetry400'] = 0; router.put('/nonretryerror/putasync/retry/400', function (req, res, next) { var pollingUri = 'http://localhost.:' + utils.getPort() + '/lro/nonretryerror/putasync/retry/failed/operationResults/400'; diff --git a/AutoRest/TestServer/server/routes/model-flatten.js b/AutoRest/TestServer/server/routes/model-flatten.js index 83b72591a030b..e5992ecd24c34 100644 --- a/AutoRest/TestServer/server/routes/model-flatten.js +++ b/AutoRest/TestServer/server/routes/model-flatten.js @@ -144,7 +144,20 @@ var modelFlatten = function (coverage) { '@odata.value': "http://foo" } } - }; + }; + + var customFlattenBodyWithInheritedProperty = { + base_product_id: "123", + base_product_description: "product description", + details: { + max_product_display_name: 'max name', + max_product_capacity: "Large", + max_product_image: { + '@odata.value': "http://foo", + 'generic_value': "https://generic" + } + } + }; router.put('/:type', function (req, res, next) { if (req.body) { if (req.params.type === 'array') { @@ -169,9 +182,9 @@ var modelFlatten = function (coverage) { utils.send400(res, next, "The received body '" + JSON.stringify(req.body) + "' did not match the expected body '" + JSON.stringify(resourceCollectionBody) + "'."); } } else if (req.params.type === 'customFlattening') { - if (_.isEqual(req.body, customFlattenBody)) { + if (_.isEqual(req.body, customFlattenBodyWithInheritedProperty)) { coverage['putModelFlattenCustomBase']++; - res.status(200).end(JSON.stringify(customFlattenBody)); + res.status(200).end(JSON.stringify(customFlattenBodyWithInheritedProperty)); } else { utils.send400(res, next, "The received body '" + JSON.stringify(req.body) + "' did not match the expected body '" + JSON.stringify(customFlattenBody) + "'."); } @@ -198,10 +211,6 @@ var modelFlatten = function (coverage) { router.put('/customFlattening/parametergrouping/:name', function (req, res, next) { if (req.body) { - console.log('>>>>>>'); - console.log(util.inspect(req.body, {depth : null})); - console.log('>>>>>><<<<<<<<<<<<<<<<<<<<<<<<<<<'); - console.log(util.inspect(customFlattenBody, {depth : null})); if (_.isEqual(req.body, customFlattenBody) && req.params.name === 'groupproduct') { coverage['putModelFlattenCustomGroupedParameter']++; res.status(200).end(JSON.stringify(customFlattenBody)); diff --git a/AutoRest/TestServer/server/routes/paths.js b/AutoRest/TestServer/server/routes/paths.js index cb4f8569b0bb2..04b5002453c3c 100644 --- a/AutoRest/TestServer/server/routes/paths.js +++ b/AutoRest/TestServer/server/routes/paths.js @@ -21,7 +21,10 @@ var scenarioMap = { "null": "Null", "2012-01-01": "Valid", "2012-01-01T01:01:01Z": "Valid", - "green color" : "Valid" + "green color" : "Valid", + "bG9yZW0" : "Base64Url", + "1460505600": "UnixTime", + "ArrayPath1,begin!*'();:@ &=+$,/?#[]end,,": "CSVInPath" }; var typeMap = { @@ -34,7 +37,8 @@ var typeMap = { "byte": "Byte", "date": "Date", "datetime": "DateTime", - "enum" : "Enum" + "enum" : "Enum", + "array": "Array" }; var getScenarioName = function (type, scenario) { @@ -47,7 +51,12 @@ var getScenarioName = function (type, scenario) { console.log('Got parsed type "' + parsedType + '" and parsed scenario "' + parsedScenario + '"\n'); return '' + parsedType + parsedScenario; -} +}; + +var validateArrayPath = function (arrayValue, separator) { + console.log('received array value "' + arrayValue + '" separator "' + separator + '"'); + return (arrayValue === "ArrayPath1" + separator + "begin!*'();:@ &=+$,/?#[]end" + separator + separator); +}; var paths = function (coverage) { router.get('/:type/empty', function (req, res, next) { @@ -78,18 +87,19 @@ var paths = function (coverage) { var test = getScenarioName(type, scenario); var bytes = new Buffer(constants.MULTIBYTE_BUFFER); - if (type === 'enum' || type === 'date' || + if (type === 'enum' || type === 'date' || type === 'array' || type === 'datetime' || scenario === 'multibyte' || (type === 'string' && - scenario.indexOf('begin') === 0)) { + scenario.indexOf('begin') === 0) || + scenario === 'bG9yZW0') { scenario = '"' + scenario + '"'; wireParameter = '"' + wireParameter + '"'; } scenario = JSON.parse(scenario); wireParameter = JSON.parse(wireParameter); - + if (test === null) { console.log("test was null\n"); utils.send400(res, next, 'Unable to parse scenario \"\/paths\/' + type + '\/' + scenario + '\"'); @@ -104,6 +114,14 @@ var paths = function (coverage) { } else { utils.send400(res, next, 'Failed string scenario \"' + scenario + '\" does not match wire parameter \"' + wireParameter + '\"'); } + } else if (type === 'array') { + if (scenario === wireParameter && validateArrayPath(wireParameter, ',')) { + console.log("Success!\n"); + coverage['UrlPaths' + test]++; + res.status(200).end(); + } else { + utils.send400(res, next, 'Failed enum scenario \"' + scenario + '\" does not match wire parameter \"' + wireParameter + '\"'); + } } else if (type === 'enum') { if (scenario === wireParameter) { console.log("Success!\n"); diff --git a/AutoRest/TestServer/server/routes/reqopt.js b/AutoRest/TestServer/server/routes/reqopt.js index 39d78407b9f0d..4e476f17e485f 100644 --- a/AutoRest/TestServer/server/routes/reqopt.js +++ b/AutoRest/TestServer/server/routes/reqopt.js @@ -44,7 +44,7 @@ var reqopt = function (coverage) { utils.send400(res, next, 'Please send a null to optional header.'); } } else if (req.params.scenario === 'body') { - if (!req.body || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { + if (req.body === undefined || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { coverage['OptionalImplicitBody']++; res.status(200).end(); } else { @@ -63,14 +63,14 @@ var reqopt = function (coverage) { var covered = "Optional" + utils.toPascalCase(req.params.type) + utils.toPascalCase(req.params.scenario); console.log('scenario: ' + covered + '\n'); if (req.params.scenario === 'parameter') { - if (!req.body || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { + if (req.body === undefined || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { coverage[covered]++; res.status(200).end(); } else { utils.send400(res, next, 'Please send a null to optional ' + req.params.type + ' body.'); } } else if (req.params.scenario === 'property') { - if (!req.body || (req.body && !req.body['value'])) { + if (req.body === undefined || (req.body && !req.body['value'])) { coverage[covered]++; res.status(200).end(); } else { diff --git a/AutoRest/TestServer/server/routes/string.js b/AutoRest/TestServer/server/routes/string.js index 400b9663f6cb7..8ab8eaf5d9abb 100644 --- a/AutoRest/TestServer/server/routes/string.js +++ b/AutoRest/TestServer/server/routes/string.js @@ -5,9 +5,12 @@ var constants = require('../util/constants'); var utils = require('../util/utils') var string = function (coverage) { + var base64String = "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjQ="; + var base64UrlString = "YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw"; + router.put('/:scenario', function (req, res, next) { if (req.params.scenario === 'null') { - if (!req.body || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { + if (req.body === undefined || (req.body && Object.keys(req.body).length === 0 && req.headers['content-length'] === '0')) { coverage['putStringNull']++; res.status(200).end(); } else { @@ -34,7 +37,15 @@ var string = function (coverage) { coverage['putStringWithLeadingAndTrailingWhitespace']++; res.status(200).end(); } - } else { + } else if (req.params.scenario === 'base64UrlEncoding') { + if (req.body !== 'YSBzdHJpbmcgdGhhdCBnZXRzIGVuY29kZWQgd2l0aCBiYXNlNjR1cmw') { + utils.send400(res, next, "Did not like base64url req '" + util.inspect(req.body) + "'"); + } else { + coverage['putStringBase64UrlEncoded']++; + res.status(200).end(); + } + } + else { utils.send400(res, next, 'Request path must contain true or false'); } }); @@ -43,6 +54,15 @@ var string = function (coverage) { if (req.params.scenario === 'null') { coverage['getStringNull']++; res.status(200).end(); + } else if (req.params.scenario === 'base64Encoding') { + coverage['getStringBase64Encoded']++; + res.status(200).end('"' + base64String + '"'); + } else if (req.params.scenario === 'base64UrlEncoding') { + coverage['getStringBase64UrlEncoded']++; + res.status(200).end('"' + base64UrlString + '"'); + } else if (req.params.scenario === 'nullBase64UrlEncoding') { + coverage['getStringNullBase64UrlEncoding']++; + res.status(200).end(); } else if (req.params.scenario === 'notProvided') { coverage['getStringNotProvided']++; res.status(200).end(); diff --git a/AutoRest/TestServer/swagger/body-array.json b/AutoRest/TestServer/swagger/body-array.json index fb015f5496264..c200959da3d6b 100644 --- a/AutoRest/TestServer/swagger/body-array.json +++ b/AutoRest/TestServer/swagger/body-array.json @@ -901,7 +901,7 @@ } } } - }, + } }, "/array/prim/date/valid": { "get": { @@ -1348,6 +1348,34 @@ } } }, + "/array/prim/base64url/valid": { + "get": { + "operationId": "array_getBase64Url", + "description": "Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded", + "tags": [ + "Array Operations" + ], + "responses": { + "200": { + "description": "Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded", + "schema": { + "description": "Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with the items base64url encoded", + "type": "array", + "items": { + "type": "string", + "format": "base64url" + } + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, "/array/complex/null": { "get": { "operationId": "array_getComplexNull", diff --git a/AutoRest/TestServer/swagger/body-dictionary.json b/AutoRest/TestServer/swagger/body-dictionary.json index e7a43e1755eef..b1065fc120df1 100644 --- a/AutoRest/TestServer/swagger/body-dictionary.json +++ b/AutoRest/TestServer/swagger/body-dictionary.json @@ -1325,6 +1325,34 @@ } } }, + "/dictionary/prim/base64url/valid": { + "get": { + "operationId": "dictionary_getBase64Url", + "description": "Get base64url dictionary value {\"0\": \"a string that gets encoded with base64url\", \"1\": \"test string\", \"2\": \"Lorem ipsum\"}", + "tags": [ + "Dictionary operations" + ], + "responses": { + "200": { + "description": "The base64url dictionary value {\"0\": \"a string that gets encoded with base64url\", \"1\": \"test string\", \"2\": \"Lorem ipsum\"}", + "schema": { + "description": "The base64url dictionary value {\"0\": \"a string that gets encoded with base64url\", \"1\": \"test string\", \"2\": \"Lorem ipsum\"}", + "type": "object", + "additionalProperties": { + "type": "string", + "format": "base64url" + } + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, "/dictionary/complex/null": { "get": { "operationId": "dictionary_getComplexNull", diff --git a/AutoRest/TestServer/swagger/body-integer.json b/AutoRest/TestServer/swagger/body-integer.json index 00b73a2c2731c..5f321e2981692 100644 --- a/AutoRest/TestServer/swagger/body-integer.json +++ b/AutoRest/TestServer/swagger/body-integer.json @@ -251,6 +251,95 @@ } } } + }, + "/int/unixtime": { + "get": { + "operationId": "int_getUnixTime", + "description": "Get datetime encoded as Unix time value", + "responses": { + "200": { + "description": "The date value encoded as Unix time", + "schema": { + "type": "integer", + "format": "unixtime" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "put": { + "operationId": "int_putUnixTimeDate", + "description": "Put datetime encoded as Unix time", + "parameters": [ + { + "name": "intBody", + "in": "body", + "schema": { + "type": "integer", + "format": "unixtime" + }, + "required": true + } + ], + "responses": { + "200": { + "description": "The datetime value encoded as Unix time" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/int/invalidunixtime": { + "get": { + "operationId": "int_getInvalidUnixTime", + "description": "Get invalid Unix time value", + "responses": { + "200": { + "description": "The invalid Unix time value", + "schema": { + "type": "integer", + "format": "unixtime" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/int/nullunixtime": { + "get": { + "operationId": "int_getNullUnixTime", + "description": "Get null Unix time value", + "responses": { + "200": { + "description": "The null Unix time value", + "schema": { + "type": "integer", + "format": "unixtime" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } } }, "definitions": { diff --git a/AutoRest/TestServer/swagger/body-string.json b/AutoRest/TestServer/swagger/body-string.json index 744ca60ec1e14..8f0afaebf0074 100644 --- a/AutoRest/TestServer/swagger/body-string.json +++ b/AutoRest/TestServer/swagger/body-string.json @@ -300,6 +300,107 @@ } } } + }, + "/string/base64Encoding": { + "get": { + "operationId": "string_getBase64Encoded", + "description": "Get value that is base64 encoded", + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "The base64 encoded string value", + "schema": { + "type": "string", + "format": "base64url" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/string/base64UrlEncoding": { + "get": { + "operationId": "string_getBase64UrlEncoded", + "description": "Get value that is base64url encoded", + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "The base64url encoded string value", + "schema": { + "type": "string", + "format": "base64url" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + }, + "put": { + "operationId": "string_putBase64UrlEncoded", + "description": "Put value that is base64url encoded", + "parameters": [ + { + "name": "stringBody", + "in": "body", + "schema": { + "type": "string", + "format": "base64url" + }, + "required": true + } + ], + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "Empty Response" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/string/nullBase64UrlEncoding": { + "get": { + "operationId": "string_getNullBase64UrlEncoded", + "description": "Get null value that is expected to be base64url encoded", + "tags": [ + "String Operations" + ], + "responses": { + "200": { + "description": "The null value", + "schema": { + "type": "string", + "format": "base64url" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } } }, "definitions": { diff --git a/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json b/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json new file mode 100644 index 0000000000000..75ef7453976ee --- /dev/null +++ b/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json @@ -0,0 +1,108 @@ +{ + "swagger": "2.0", + "info": { + "title": "AutoRest Parameterized Custom Host Test Client", + "description": "Test Infrastructure for AutoRest", + "version": "1.0.0" + }, + "x-ms-parameterized-host": { + "hostTemplate": "{vault}{secret}{dnsSuffix}", + "useSchemePrefix": false, + "parameters": [ + { + "name": "vault", + "description": "The vault name, e.g. https://myvault", + "required": true, + "type": "string", + "in": "path", + "x-ms-skip-url-encoding": true + }, + { + "name": "secret", + "description": "Secret value.", + "required": true, + "type": "string", + "in": "path", + "x-ms-skip-url-encoding": true + }, + { + "$ref": "#/parameters/dnsSuffix" + } + ] + }, + "produces": [ "application/json" ], + "consumes": [ "application/json" ], + "paths": { + "/customuri/{subscriptionId}/{keyName}": { + "get": { + "operationId": "paths_getEmpty", + "description": "Get a 200 to test a valid base uri", + "tags": [ + "Path Operations" + ], + "parameters": [ + { + "name": "keyName", + "in": "path", + "required": true, + "type": "string", + "description": "The key name with value 'key1'." + }, + { + "$ref": "#/parameters/SubscriptionIdParameter" + }, + { + "name": "keyVersion", + "in": "query", + "required": false, + "type": "string", + "default": "v1", + "description": "The key version. Default value 'v1'." + } + ], + "responses": { + "200": { + "description": "Successfully received a 200 response" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + } + }, + "parameters": { + "SubscriptionIdParameter": { + "name": "subscriptionId", + "in": "path", + "required": true, + "type": "string", + "description": "The subscription id with value 'test12'." + }, + "dnsSuffix": { + "name": "dnsSuffix", + "description": "A string value that is used as a global part of the parameterized host. Default value 'host'.", + "type": "string", + "required": false, + "default": "host", + "in": "path", + "x-ms-skip-url-encoding": true + } + }, + "definitions": { + "Error": { + "properties": { + "status": { + "type": "integer", + "format": "int32" + }, + "message": { + "type": "string" + } + } + } + } +} diff --git a/AutoRest/TestServer/swagger/custom-baseUrl.json b/AutoRest/TestServer/swagger/custom-baseUrl.json index 5ca07d1627a06..aaa0309f4b94a 100644 --- a/AutoRest/TestServer/swagger/custom-baseUrl.json +++ b/AutoRest/TestServer/swagger/custom-baseUrl.json @@ -8,6 +8,7 @@ "host": "badhost", "x-ms-parameterized-host": { "hostTemplate": "{accountName}{host}", + "positionInOperation": "last", "parameters": [ { "name": "accountName", diff --git a/AutoRest/TestServer/swagger/lro.json b/AutoRest/TestServer/swagger/lro.json index b064ce8c3aa2d..9f9bba0c26759 100644 --- a/AutoRest/TestServer/swagger/lro.json +++ b/AutoRest/TestServer/swagger/lro.json @@ -1772,6 +1772,46 @@ } } } + }, + "/lro/nonretryerror/put/201/creating/400/invalidjson": { + "put": { + "x-ms-long-running-operation": true, + "operationId": "LROSADs_putNonRetry201Creating400InvalidJson", + "description": "Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code", + "tags": [ + "LROSAD Operations" + ], + "parameters": [ + { + "name": "product", + "description": "Product to put", + "in": "body", + "schema": { + "$ref": "#/definitions/Product" + } + } + ], + "responses": { + "200": { + "description": "Response after completion, with ProvisioningState='Succeeded'", + "schema": { + "$ref": "#/definitions/Product" + } + }, + "201": { + "description": "Initial response, with ProvisioningState = 'Creating'", + "schema": { + "$ref": "#/definitions/Product" + } + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/CloudError" + } + } + } + } }, "/lro/nonretryerror/putasync/retry/400": { "put": { diff --git a/AutoRest/TestServer/swagger/model-flattening.json b/AutoRest/TestServer/swagger/model-flattening.json index 2bd49e97414b0..0ad7424f78cc3 100644 --- a/AutoRest/TestServer/swagger/model-flattening.json +++ b/AutoRest/TestServer/swagger/model-flattening.json @@ -433,8 +433,18 @@ } } }, + "GenericUrl": { + "description": "The Generic URL.", + "properties": { + "generic_value": { + "type": "string", + "description": "Generic URL value." + } + } + }, "ProductUrl": { "description": "The product URL.", + "allOf": [ { "$ref": "#/definitions/GenericUrl" } ], "properties": { "@odata.value": { "type": "string", diff --git a/AutoRest/TestServer/swagger/url.json b/AutoRest/TestServer/swagger/url.json index 6a8ab8f526e17..670ff00f9bd1d 100644 --- a/AutoRest/TestServer/swagger/url.json +++ b/AutoRest/TestServer/swagger/url.json @@ -710,6 +710,99 @@ } } }, + "/paths/string/bG9yZW0/{base64UrlPath}": { + "get": { + "operationId": "paths_base64Url", + "description": "Get 'lorem' encoded value as 'bG9yZW0' (base64url)", + "tags": [ + "Path Operations" + ], + "parameters": [ + { + "name": "base64UrlPath", + "in": "path", + "description": "base64url encoded value", + "type": "string", + "format": "base64url", + "required": true + } + ], + "responses": { + "200": { + "description": "Successfully Received 'lorem' encoded value as 'bG9yZW0' (base64url)" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath}": { + "get": { + "operationId": "paths_ArrayCsvInPath", + "description": "Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format", + "tags": [ + "query Operations" + ], + "parameters": [ + { + "name": "arrayPath", + "in": "path", + "required": true, + "description": "an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the csv-array format", + "type": "array", + "items": { + "type": "string" + }, + "collectionFormat": "csv" + } + ], + "responses": { + "200": { + "description": "Successfully received /paths/array/ArrayPath1,begin!*'();:@ &=+$,/?#[]end,,/ArrayPath1,begin!*'();:@ &=+$,/?#[]end,," + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, + "/paths/int/1460505600/{unixTimeUrlPath}": { + "get": { + "operationId": "paths_unixTimeUrl", + "description": "Get the date 2016-04-13 encoded value as '1460505600' (Unix time)", + "tags": [ + "Path Operations" + ], + "parameters": [ + { + "name": "unixTimeUrlPath", + "in": "path", + "description": "Unix time encoded value", + "type": "integer", + "format": "unixtime", + "required": true + } + ], + "responses": { + "200": { + "description": "Successfully Received date 2016-04-13 encoded value as '1460505600' (Unix time)" + }, + "default": { + "description": "Unexpected error", + "schema": { + "$ref": "#/definitions/Error" + } + } + } + } + }, "/queries/bool/true": { "get": { "operationId": "queries_getBooleanTrue", diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/LongRunningOperationsTest.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/LongRunningOperationsTest.cs index bf999fe9f7c1b..1d0bb2069f1bf 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/LongRunningOperationsTest.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/LongRunningOperationsTest.cs @@ -104,6 +104,19 @@ public void TestAsyncOperationWithMissingProvisioningState() Assert.Equal("100", resource.Id); } + [Fact] + public void TestAsyncOperationWithNonSuccessStatusAndInvalidResponseContent() + { + var tokenCredentials = new TokenCredentials("123", "abc"); + var handler = new PlaybackTestHandler(MockAsyncOperaionWithNonSuccessStatusAndInvalidResponseContent()); + var fakeClient = new RedisManagementClient(tokenCredentials, handler); + fakeClient.LongRunningOperationInitialTimeout = fakeClient.LongRunningOperationRetryTimeout = 0; + var error = Assert.Throws(() => + fakeClient.RedisOperations.Delete("rg", "redis", "1234")); + Assert.Equal("Long running operation failed with status 'BadRequest'.", error.Message); + Assert.Null(error.Body); + } + [Fact] public void TestPutOperationWithoutProvisioningState() { @@ -737,6 +750,22 @@ private IEnumerable MockAsyncOperaionWithMissingProvisionin yield return response3; } + private IEnumerable MockAsyncOperaionWithNonSuccessStatusAndInvalidResponseContent() + { + var response1 = new HttpResponseMessage(HttpStatusCode.Accepted) + { + Content = new StringContent("") + }; + response1.Headers.Add("Location", "http://custom/status"); + yield return response1; + + var response2 = new HttpResponseMessage(HttpStatusCode.BadRequest) + { + Content = new StringContent("<") + }; + yield return response2; + } + private IEnumerable MockPutOperaionWithoutProvisioningStateInResponse() { var response1 = new HttpResponseMessage(HttpStatusCode.Created) diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs index c651bbdc33621..e267142696404 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure.Tests/ODataTests.cs @@ -7,6 +7,7 @@ using Microsoft.Rest.Azure.OData; using Newtonsoft.Json; using Xunit; +using System.Collections.Generic; namespace Microsoft.Rest.ClientRuntime.Azure.Test { @@ -248,14 +249,44 @@ public void ODataQuerySupportsEmptyState() { Value = null }; + var paramEncoded = new InputParam1 + { + Value = "bar/car" + }; query = new ODataQuery(p => p.Foo == param.Value); Assert.Equal("", query.ToString()); query = new ODataQuery(p => p.Foo == param.Value && p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); query = new ODataQuery(p => p.AssignedTo(param.Value)); Assert.Equal("", query.ToString()); + query = new ODataQuery(p => p.AssignedTo(paramEncoded.Value)); + Assert.Equal("$filter=assignedTo('bar%2Fcar')", query.ToString()); + } + + [Fact] + public void ODataQuerySupportsCustomDateTimeOffsetFilter() + { + var param = new Param1 + { + SubmitTime = DateTimeOffset.Parse("2016-03-28T08:15:00.0971693+00:00"), + State = "Ended" + + }; + + var filter = new List(); + filter.Add(string.Format("submitTime lt datetimeoffset'{0}'", Uri.EscapeDataString(param.SubmitTime.Value.ToString("O")))); + filter.Add(string.Format("state ne '{0}'", param.State)); + var filterString = string.Join(" and ", filter.ToArray()); + + + var query = new ODataQuery + { + Filter = filterString + }; + Assert.Equal("$filter=submitTime lt datetimeoffset'2016-03-28T08%3A15%3A00.0971693%2B00%3A00' and state ne 'Ended'", query.ToString()); } + [Fact] public void ODataQuerySupportsPartialState() { @@ -266,6 +297,17 @@ public void ODataQuerySupportsPartialState() Assert.Equal("$filter=foo eq 'bar'&$top=100", query.ToString()); } + [Fact] + public void ODataQuerySupportsPartialStateWithSlashes() + { + var queryString = "$filter=foo eq 'bar%2Fclub'&$top=100"; + var query = new ODataQuery(p => p.Foo == "bar/club") + { + Top = 100 + }; + Assert.Equal(queryString, query.ToString()); + } + [Fact] public void ODataQuerySupportsImplicitConversionFromFilterString() { @@ -318,7 +360,7 @@ public void ODataQuerySupportsMethod() var filterString = FilterString.Generate(parameters => parameters.AtScope() && parameters.AssignedTo(param.Value)); - Assert.Equal(filterString, "atScope() and assignedTo('Microsoft.Web%2Fsites')"); + Assert.Equal("atScope() and assignedTo('Microsoft.Web%2Fsites')", filterString); } } @@ -356,6 +398,10 @@ public class Param1 [JsonProperty("d")] public DateTime Date { get; set; } public DateTime Date2 { get; set; } + [JsonProperty("submitTime")] + public DateTimeOffset? SubmitTime { get; set; } + [JsonProperty("state")] + public string State { get; set; } [JsonProperty("vals")] public string[] Values { get; set; } [JsonProperty("param2")] diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs index 57bbd064b95c2..422f074bd3028 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/AzureClientExtensions.cs @@ -122,6 +122,38 @@ await UpdateStateFromGetResourceOperation(client, pollingState, getOperationUrl, return pollingState.AzureOperationResponse; } + /// + /// Gets operation result for PUT and PATCH operations. + /// + /// IAzureClient + /// Response from the begin operation + /// Headers that will be added to request + /// Cancellation token + /// Operation response + public static async Task GetPutOrPatchOperationResultAsync( + this IAzureClient client, + AzureOperationResponse response, + Dictionary> customHeaders, + CancellationToken cancellationToken) + { + var newResponse = new AzureOperationResponse + { + Request = response.Request, + Response = response.Response, + RequestId = response.RequestId + }; + + var azureOperationResponse = await client.GetPutOrPatchOperationResultAsync( + newResponse, customHeaders, cancellationToken); + + return new AzureOperationResponse + { + Request = azureOperationResponse.Request, + Response = azureOperationResponse.Response, + RequestId = azureOperationResponse.RequestId + }; + } + /// /// Gets operation result for DELETE and POST operations. /// @@ -599,7 +631,16 @@ private static async Task> GetRawAsync( statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent) { - CloudError errorBody = SafeJsonConvert.DeserializeObject(responseContent, client.DeserializationSettings); + CloudError errorBody = null; + try + { + errorBody = SafeJsonConvert.DeserializeObject(responseContent, client.DeserializationSettings); + } + catch (JsonException) + { + // failed to deserialize, return empty body + } + throw new CloudException(string.Format(CultureInfo.InvariantCulture, Resources.LongRunningOperationFailed, statusCode)) { diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/Properties/AssemblyInfo.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/Properties/AssemblyInfo.cs index 727ccfd166cca..501abc07659ad 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/Properties/AssemblyInfo.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/Properties/AssemblyInfo.cs @@ -9,7 +9,7 @@ [assembly: AssemblyTitle("Microsoft Rest Azure Client Runtime")] [assembly: AssemblyDescription("Client infrastructure for Azure client libraries.")] [assembly: AssemblyVersion("3.0.0.0")] -[assembly: AssemblyFileVersion("3.1.0.0")] +[assembly: AssemblyFileVersion("3.2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json index 6f416ef8ea5b4..6a24bd8b0ca07 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime.Azure/project.json @@ -1,5 +1,5 @@ { - "version": "3.1.0", + "version": "3.2.0", "copyright": "Copyright (c) Microsoft Corporation", "iconUrl": "http://go.microsoft.com/fwlink/?LinkID=288890", "title": "Client Runtime for Microsoft Azure Libraries", diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Properties/AssemblyInfo.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Properties/AssemblyInfo.cs index 896b8469346f6..14749d7e07285 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Properties/AssemblyInfo.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Properties/AssemblyInfo.cs @@ -9,7 +9,7 @@ [assembly: AssemblyTitle("Microsoft Rest Client Runtime")] [assembly: AssemblyDescription("Client infrastructure for client libraries generated by AutoRest.")] [assembly: AssemblyVersion("2.0.0.0")] -[assembly: AssemblyFileVersion("2.1.0.0")] +[assembly: AssemblyFileVersion("2.2.0.0")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft Corporation")] diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/Base64UrlJsonConverter.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/Base64UrlJsonConverter.cs new file mode 100644 index 0000000000000..3120ec92c4841 --- /dev/null +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/Base64UrlJsonConverter.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Microsoft.Rest.Serialization +{ + public class Base64UrlJsonConverter : JsonConverter + { + /// + /// Converts a byte array to a Base64Url encoded string + /// + /// The byte array to convert + /// The Base64Url encoded form of the input + private static string ToBase64UrlString(byte[] input) + { + if (input == null) + throw new ArgumentNullException("input"); + + return Convert.ToBase64String(input).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + } + + /// + /// Converts a Base64Url encoded string to a byte array + /// + /// The Base64Url encoded string + /// The byte array represented by the enconded string + private static byte[] FromBase64UrlString(string input) + { + if (string.IsNullOrEmpty(input)) + throw new ArgumentNullException("input"); + + return Convert.FromBase64String(Pad(input.Replace('-', '+').Replace('_', '/'))); + } + + /// + /// Adds padding to the input + /// + /// the input string + /// the padded string + private static string Pad(string input) + { + var count = 3 - ((input.Length + 3) % 4); + + if (count == 0) + { + return input; + } + + return input + new string('=', count); + } + + public override bool CanConvert(Type objectType) + { + if (objectType == typeof(byte[])) + return true; + + return false; + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (objectType != typeof(byte[])) + { + return serializer.Deserialize(reader, objectType); + } + else + { + var value = serializer.Deserialize(reader); + + if (!string.IsNullOrEmpty(value)) + { + return FromBase64UrlString(value); + } + } + + return null; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value.GetType() != typeof(byte[])) + { + JToken.FromObject(value).WriteTo(writer); + } + else + { + JToken.FromObject(ToBase64UrlString((byte[])value)).WriteTo(writer); + } + } + } +} \ No newline at end of file diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs new file mode 100644 index 0000000000000..fd345541a6de0 --- /dev/null +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/Serialization/UnixTimeJsonConverter.cs @@ -0,0 +1,77 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; + +namespace Microsoft.Rest.Serialization +{ + public class UnixTimeJsonConverter : JsonConverter + { + public static readonly DateTime EpochDate = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); + + /// + /// Converts a byte array to a Base64Url encoded string + /// + /// The byte array to convert + /// The Base64Url encoded form of the input + private static long? ToUnixTime(DateTime dateTime) + { + return (long?)dateTime.Subtract(EpochDate).TotalSeconds; + } + + /// + /// Converts a Base64Url encoded string to a byte array + /// + /// The Base64Url encoded string + /// The byte array represented by the enconded string + private static DateTime? FromUnixTime(long? seconds) + { + if (seconds.HasValue) + { + return EpochDate.AddSeconds(seconds.Value); + } + return null; + } + + public override bool CanConvert(Type objectType) + { + if (objectType == typeof(DateTime?) || objectType == typeof(DateTime)) + return true; + + return false; + } + + public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) + { + if (objectType != typeof(DateTime?)) + { + return serializer.Deserialize(reader, objectType); + } + else + { + var value = serializer.Deserialize(reader); + + if (value.HasValue) + { + return FromUnixTime(value); + } + } + + return null; + } + + public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) + { + if (value.GetType() != typeof(DateTime)) + { + JToken.FromObject(value).WriteTo(writer); + } + else + { + JToken.FromObject(ToUnixTime((DateTime)value)).WriteTo(writer); + } + } + } +} \ No newline at end of file diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/TransientFaultHandling/ExponentialBackoffRetryStrategy.cs b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/TransientFaultHandling/ExponentialBackoffRetryStrategy.cs index cbe87e573cf61..b1241b6dcbe6c 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/TransientFaultHandling/ExponentialBackoffRetryStrategy.cs +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/TransientFaultHandling/ExponentialBackoffRetryStrategy.cs @@ -112,10 +112,10 @@ public override ShouldRetryHandler GetShouldRetryHandler() { var random = new Random(); - var delta = (int) ((Math.Pow(2.0, currentRetryCount) - 1.0)* - random.Next((int) (_deltaBackoff.TotalMilliseconds*0.8), - (int) (_deltaBackoff.TotalMilliseconds*1.2))); - var interval = (int) Math.Min(checked(_minBackoff.TotalMilliseconds + delta), + var delta = (Math.Pow(2.0, currentRetryCount) - 1.0) * + random.Next((int) (_deltaBackoff.TotalMilliseconds*0.8), + (int) (_deltaBackoff.TotalMilliseconds*1.2)); + var interval = (int) Math.Min(_minBackoff.TotalMilliseconds + delta, _maxBackoff.TotalMilliseconds); TimeSpan retryInterval = TimeSpan.FromMilliseconds(interval); diff --git a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/project.json b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/project.json index 59c06562130e3..82724c95bf56c 100644 --- a/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/project.json +++ b/ClientRuntimes/CSharp/Microsoft.Rest.ClientRuntime/project.json @@ -1,5 +1,5 @@ { - "version": "2.1.0", + "version": "2.2.0", "copyright": "Copyright (c) Microsoft Corporation", "iconUrl": "https://cdn.rawgit.com/Azure/AutoRest/7c1576dfb56974176223545cfac5762d168ded5f/Documentation/images/autorest-small-flat.png", "title": "Client Runtime Library for Microsoft AutoRest Generated Clients", diff --git a/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java b/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java index a50faee9cf16a..3e995fb06a087 100644 --- a/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java +++ b/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/ApplicationTokenCredentials.java @@ -13,6 +13,7 @@ import com.microsoft.rest.credentials.TokenCredentials; import java.io.IOException; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** @@ -103,7 +104,8 @@ public void refreshToken() throws IOException { private void acquireAccessToken() throws IOException { String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); - AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), Executors.newSingleThreadExecutor()); + ExecutorService executor = Executors.newSingleThreadExecutor(); + AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), executor); try { authenticationResult = context.acquireToken( this.getEnvironment().getTokenAudience(), @@ -111,6 +113,8 @@ private void acquireAccessToken() throws IOException { null).get(); } catch (Exception e) { throw new IOException(e.getMessage(), e); + } finally { + executor.shutdown(); } } } diff --git a/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java b/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java index 995f32fabc4a1..af02c07507b74 100644 --- a/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java +++ b/ClientRuntimes/Java/azure-client-authentication/src/main/java/com/microsoft/azure/credentials/UserTokenCredentials.java @@ -13,6 +13,7 @@ import java.io.IOException; import java.util.Date; +import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** @@ -146,7 +147,8 @@ private void acquireAccessToken() throws IOException { private void acquireAccessTokenFromRefreshToken() throws IOException { String authorityUrl = this.getEnvironment().getAuthenticationEndpoint() + this.getDomain(); - AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), Executors.newSingleThreadExecutor()); + ExecutorService executor = Executors.newSingleThreadExecutor(); + AuthenticationContext context = new AuthenticationContext(authorityUrl, this.getEnvironment().isValidateAuthority(), executor); try { authenticationResult = context.acquireTokenByRefreshToken( authenticationResult.getRefreshToken(), @@ -154,6 +156,8 @@ private void acquireAccessTokenFromRefreshToken() throws IOException { null, null).get(); } catch (Exception e) { throw new IOException(e.getMessage(), e); + } finally { + executor.shutdown(); } } } diff --git a/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java b/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java index 77c8c6c0e48cf..2f3569fc51c59 100644 --- a/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java +++ b/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/AzureClient.java @@ -355,7 +355,7 @@ public AsyncPollingTask getPostOrDeleteResultAsync(Response } else { responseBody = response.errorBody(); } - if (statusCode != 200 && statusCode != 201 && statusCode != 202) { + if (statusCode != 200 && statusCode != 202 && statusCode != 204) { CloudException exception = new CloudException(statusCode + " is not a valid polling status code"); exception.setResponse(response); try { diff --git a/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java b/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java index 8c42851d4e851..e13926390c42f 100644 --- a/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java +++ b/ClientRuntimes/Java/azure-client-runtime/src/main/java/com/microsoft/azure/PagedList.java @@ -7,6 +7,8 @@ package com.microsoft.azure; +import com.microsoft.rest.AutoRestException; + import java.io.IOException; import java.util.Collection; import java.util.Iterator; @@ -44,10 +46,10 @@ public PagedList(Page page) { * * @param nextPageLink the link to get the next page of items. * @return the {@link Page} object storing a page of items and a link to the next page. - * @throws CloudException thrown if an error is raised from Azure. + * @throws AutoRestException thrown if an error is raised from Azure. * @throws IOException thrown if there's any failure in deserialization. */ - public abstract Page nextPage(String nextPageLink) throws CloudException, IOException; + public abstract Page nextPage(String nextPageLink) throws AutoRestException, IOException; /** * If there are more pages available. @@ -67,7 +69,7 @@ public void loadNextPage() { Page nextPage = nextPage(this.nextPageLink); this.nextPageLink = nextPage.getNextPageLink(); this.items.addAll(nextPage.getItems()); - } catch (CloudException e) { + } catch (AutoRestException e) { throw new WebServiceException(e.toString(), e); } catch (IOException e) { throw new DataBindingException(e.getMessage(), e); diff --git a/ClientRuntimes/Java/client-runtime/build.gradle b/ClientRuntimes/Java/client-runtime/build.gradle index 47cbaf08c6397..b734d33608eaf 100644 --- a/ClientRuntimes/Java/client-runtime/build.gradle +++ b/ClientRuntimes/Java/client-runtime/build.gradle @@ -25,7 +25,7 @@ dependencies { compile 'com.google.guava:guava:18.0' compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4' compile 'com.squareup.okhttp3:okhttp:3.2.0' - compile ('com.squareup.okio:okio:1.7.0-SNAPSHOT') { changing = true } + compile 'com.squareup.okio:okio:1.7.0' compile 'com.squareup.okhttp3:logging-interceptor:3.1.1' compile 'com.squareup.okhttp3:okhttp-urlconnection:3.1.1' compile 'com.squareup.retrofit2:converter-jackson:2.0.0-beta4' diff --git a/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java b/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java index 2915ae5e44b8d..1fae7e4e9fe51 100644 --- a/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java +++ b/ClientRuntimes/Java/client-runtime/src/main/java/com/microsoft/rest/ServiceResponseBuilder.java @@ -239,7 +239,9 @@ public ServiceResponseWithHeaders buildEmptyWithHeaders(Re THeader headers = mapperAdapter.deserialize( mapperAdapter.serialize(response.headers()), headerType); - return new ServiceResponseWithHeaders<>(headers, bodyResponse.getHeadResponse()); + ServiceResponseWithHeaders serviceResponse = new ServiceResponseWithHeaders<>(headers, bodyResponse.getHeadResponse()); + serviceResponse.setBody(bodyResponse.getBody()); + return serviceResponse; } /** @@ -272,7 +274,6 @@ protected Object buildBody(int statusCode, ResponseBody responseBody) throws IOE // Return raw response if InputStream is the target type else if (type == InputStream.class) { InputStream stream = responseBody.byteStream(); - responseBody.close(); return stream; } // Deserialize diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/package.json b/ClientRuntimes/NodeJS/ms-rest-azure/package.json index da011dad01070..0cb2731447104 100644 --- a/ClientRuntimes/NodeJS/ms-rest-azure/package.json +++ b/ClientRuntimes/NodeJS/ms-rest-azure/package.json @@ -5,7 +5,7 @@ "email": "azsdkteam@microsoft.com", "url": "https://github.com/Azure/AutoRest" }, - "version": "1.11.0", + "version": "1.12.0", "description": "Client Runtime for Node.js Azure client libraries generated using AutoRest", "tags": [ "node", "microsoft", "autorest", "azure", "clientruntime" ], "keywords": [ "node", "microsoft", "autorest", "azure", "clientruntime" ], @@ -23,7 +23,7 @@ "async": "0.2.7", "uuid": "2.0.1", "adal-node": "0.1.17", - "ms-rest": "^1.11.0", + "ms-rest": "^1.12.0", "underscore": "^1.4.0", "moment": "^2.6.0" }, diff --git a/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js index f9810f5ec7bf6..de8d0778efd92 100644 --- a/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js +++ b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js @@ -78,6 +78,8 @@ exports.serialize = function (mapper, object, objectName) { payload = serializeDateTypes.call(this, mapperType, object, objectName); } else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = serializeBufferType.call(this, objectName, object); + } else if (mapperType.match(/^Base64Url$/ig) !== null) { + payload = serializeBase64UrlType.call(this, objectName, object); } else if (mapperType.match(/^Sequence$/ig) !== null) { payload = serializeSequenceType.call(this, mapper, object, objectName); } else if (mapperType.match(/^Dictionary$/ig) !== null) { @@ -338,6 +340,16 @@ function serializeBufferType(objectName, value) { return value; } +function serializeBase64UrlType(objectName, value) { + if (value !== null && value !== undefined) { + if (!Buffer.isBuffer(value)) { + throw new Error(util.format('%s must be of type Buffer.', objectName)); + } + value = bufferToBase64Url(value); + } + return value; +} + function serializeDateTypes(typeName, value, objectName) { if (value !== null && value !== undefined) { if (typeName.match(/^Date$/ig) !== null) { @@ -394,6 +406,8 @@ exports.deserialize = function (mapper, responseBody, objectName) { payload = moment.duration(responseBody); } else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = new Buffer(responseBody, 'base64'); + } else if (mapperType.match(/^Base64Url$/ig) !== null) { + payload = base64UrlToBuffer(responseBody); } else if (mapperType.match(/^Sequence$/ig) !== null) { payload = deserializeSequenceType.call(this, mapper, responseBody, objectName); } else if (mapperType.match(/^Dictionary$/ig) !== null) { @@ -547,4 +561,38 @@ function splitSerializeName(prop) { return classes; } +function bufferToBase64Url(buffer) { + if (!buffer) { + return null; + } + if (!Buffer.isBuffer(buffer)) { + throw new Error('Please provide an input of type Buffer for converting to Base64Url.'); + } + // Buffer to Base64. + var str = buffer.toString('base64'); + // Base64 to Base64Url. + return trimEnd(str, '=').replace(/\+/g, '-').replace(/\//g, '_'); +} + +function trimEnd(str, ch) { + var len = str.length; + while ((len - 1) >= 0 && str[len - 1] === ch) { + --len; + } + return str.substr(0, len); +} + +function base64UrlToBuffer(str) { + if (!str) { + return null; + } + if (str && typeof str.valueOf() !== 'string') { + throw new Error('Please provide an input of type string for converting to Buffer'); + } + // Base64Url to Base64. + str = str.replace(/\-/g, '+').replace(/\_/g, '/'); + // Base64 to Buffer. + return new Buffer(str, 'base64'); +} + exports = module.exports; \ No newline at end of file diff --git a/ClientRuntimes/NodeJS/ms-rest/package.json b/ClientRuntimes/NodeJS/ms-rest/package.json index 76fe82cddb802..b21efcee2df2c 100644 --- a/ClientRuntimes/NodeJS/ms-rest/package.json +++ b/ClientRuntimes/NodeJS/ms-rest/package.json @@ -5,7 +5,7 @@ "email": "azsdkteam@microsoft.com", "url": "https://github.com/Azure/AutoRest" }, - "version": "1.11.0", + "version": "1.12.0", "description": "Client Runtime for Node.js client libraries generated using AutoRest", "tags": ["node", "microsoft", "autorest", "clientruntime"], "keywords": ["node", "microsoft", "autorest", "clientruntime"], @@ -26,7 +26,7 @@ "request": "2.69.0", "duplexer": "~0.1.1", "through": "~2.3.4", - "moment": "^2.6.0" + "moment": "^2.9.0" }, "devDependencies": { "jshint": "2.6.3", diff --git a/ClientRuntimes/Python/msrest/doc/conf.py b/ClientRuntimes/Python/msrest/doc/conf.py index bad75ae0d6139..1dfe56981ffc9 100644 --- a/ClientRuntimes/Python/msrest/doc/conf.py +++ b/ClientRuntimes/Python/msrest/doc/conf.py @@ -57,9 +57,9 @@ # built documents. # # The short X.Y version. -version = '0.1.3' +version = '0.2.0' # The full version, including alpha/beta/rc tags. -release = '0.1.3' +release = '0.2.0' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/ClientRuntimes/Python/msrest/msrest/http_logger.py b/ClientRuntimes/Python/msrest/msrest/http_logger.py index b19405528cf96..5159a996a6e8f 100644 --- a/ClientRuntimes/Python/msrest/msrest/http_logger.py +++ b/ClientRuntimes/Python/msrest/msrest/http_logger.py @@ -81,8 +81,8 @@ def log_response(adapter, request, response, *args, **kwargs): _LOGGER.debug("Body contains binary data.") elif result.headers.get("content-type", "").startswith("image"): _LOGGER.debug("Body contains image data.") - # elif result.headers.get("transfer-encoding") == 'chunked': - # LOGGER.debug("Body contains chunked data.") + elif result.headers.get("transfer-encoding") == 'chunked': + _LOGGER.debug("Body contains chunked data.") else: _LOGGER.debug(str(result.content)) return result diff --git a/ClientRuntimes/Python/msrest/msrest/pipeline.py b/ClientRuntimes/Python/msrest/msrest/pipeline.py index a4996a20d7e48..a376139a22f1a 100644 --- a/ClientRuntimes/Python/msrest/msrest/pipeline.py +++ b/ClientRuntimes/Python/msrest/msrest/pipeline.py @@ -205,7 +205,7 @@ def add_content(self, data): :param data: Request body data, can be a json serializable object (e.g. dictionary) or a generator (e.g. file data). """ - if data is None and self.method == 'GET': + if data is None: return try: diff --git a/ClientRuntimes/Python/msrest/msrest/serialization.py b/ClientRuntimes/Python/msrest/msrest/serialization.py index 256f6379fb2b4..4675cd6aacee7 100644 --- a/ClientRuntimes/Python/msrest/msrest/serialization.py +++ b/ClientRuntimes/Python/msrest/msrest/serialization.py @@ -186,7 +186,8 @@ def _serialize(self, target_obj, data_type=None, **kwargs): attr_type = map['type'] orig_attr = getattr(target_obj, attr) validation = target_obj._validation.get(attr_name, {}) - self.validate(orig_attr, attr_name, **validation) + orig_attr = self.validate( + orig_attr, attr_name, **validation) new_attr = self.serialize_data( orig_attr, attr_type, **kwargs) @@ -245,7 +246,7 @@ def url(self, name, data, data_type, **kwargs): :raises: TypeError if serialization fails. :raises: ValueError if data is None """ - self.validate(data, name, required=True, **kwargs) + data = self.validate(data, name, required=True, **kwargs) try: output = self.serialize_data(data, data_type, **kwargs) if data_type == 'bool': @@ -269,7 +270,7 @@ def query(self, name, data, data_type, **kwargs): :raises: TypeError if serialization fails. :raises: ValueError if data is None """ - self.validate(data, name, required=True, **kwargs) + data = self.validate(data, name, required=True, **kwargs) try: if data_type in ['[str]']: data = ["" if d is None else d for d in data] @@ -295,7 +296,7 @@ def header(self, name, data, data_type, **kwargs): :raises: TypeError if serialization fails. :raises: ValueError if data is None """ - self.validate(data, name, required=True, **kwargs) + data = self.validate(data, name, required=True, **kwargs) try: if data_type in ['[str]']: data = ["" if d is None else d for d in data] @@ -315,6 +316,8 @@ def validate(self, data, name, **kwargs): raise ValidationError("required", name, True) elif data is None: return + elif kwargs.get('readonly'): + return try: for key, value in kwargs.items(): @@ -323,6 +326,8 @@ def validate(self, data, name, **kwargs): raise ValidationError(key, name, value) except TypeError: raise ValidationError("unknown", name) + else: + return data def serialize_data(self, data, data_type, **kwargs): """Serialize generic data according to supplied data type. @@ -406,7 +411,8 @@ def serialize_iter(self, data, iter_type, div=None, **kwargs): serialized.append(None) if div: - return div.join(serialized) + serialized = ['' if s is None else s for s in serialized] + serialized = div.join(serialized) return serialized def serialize_dict(self, attr, dict_type, **kwargs): @@ -590,7 +596,7 @@ def __call__(self, target_obj, response_data): :param str target_obj: Target data type to deserialize to. :param requests.Response response_data: REST response object. :raises: DeserializationError if deserialization fails. - :returns: Deserialized object. + :return: Deserialized object. """ data = self._unpack_content(response_data) response, class_name = self._classify_target(target_obj, data) @@ -686,21 +692,32 @@ def _instantiate_model(self, response, attrs): :param response: The response model class. :param d_attrs: The deserialized response attributes. """ - subtype = response._get_subtype_map() - try: - kwargs = {k: v for k, v in attrs.items() if k not in subtype} - return response(**kwargs) - except TypeError: - pass - - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to instantiate or populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) + if callable(response): + subtype = response._get_subtype_map() + try: + readonly = [k for k, v in response._validation.items() + if v.get('readonly')] + const = [k for k, v in response._validation.items() + if v.get('constant')] + kwargs = {k: v for k, v in attrs.items() + if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format( + kwargs, response) + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) def deserialize_data(self, data, data_type): """Process data for deserialization according to data type. @@ -708,7 +725,7 @@ def deserialize_data(self, data, data_type): :param str data: The response string to be deserialized. :param str data_type: The type to deserialize to. :raises: DeserializationError if deserialization fails. - :returns: Deserialized object. + :return: Deserialized object. """ if data is None: return data @@ -850,6 +867,14 @@ def deserialize_enum(self, data, enum_obj): :rtype: Enum :raises: DeserializationError if string is not valid enum value. """ + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + # https://github.com/Azure/azure-rest-api-specs/issues/141 + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) try: return enum_obj(str(data)) except ValueError: diff --git a/ClientRuntimes/Python/msrest/msrest/service_client.py b/ClientRuntimes/Python/msrest/msrest/service_client.py index 14ea3f3cff2b8..a204089838ddc 100644 --- a/ClientRuntimes/Python/msrest/msrest/service_client.py +++ b/ClientRuntimes/Python/msrest/msrest/service_client.py @@ -117,6 +117,7 @@ def _configure_session(self, session, **config): session.headers.update(self._headers) session.headers['User-Agent'] = self.config.user_agent + session.headers['Accept'] = 'application/json' session.max_redirects = config.get( 'max_redirects', self.config.redirect_policy()) session.proxies = config.get( @@ -145,7 +146,7 @@ def send_formdata(self, request, headers={}, content={}, **config): :param ClientRequest request: The request object to be sent. :param dict headers: Any headers to add to the request. :param dict content: Dictionary of the fields of the formdata. - :param config: Any specific config overrides + :param config: Any specific config overrides. """ file_data = {f: self._format_data(d) for f, d in content.items()} try: @@ -162,6 +163,7 @@ def send(self, request, headers=None, content=None, **config): :param content: Any body data to add to the request. :param config: Any specific config overrides """ + response = None session = self.creds.signed_session() kwargs = self._configure_session(session, **config) @@ -203,7 +205,8 @@ def send(self, request, headers=None, content=None, **config): msg = "Error occurred in request." raise_with_traceback(ClientRequestError, msg, err) finally: - session.close() + if not response or response._content_consumed: + session.close() def stream_download(self, data, callback): """Generator for streaming request body data. @@ -228,6 +231,7 @@ def stream_download(self, data, callback): callback(chunk, response=data) yield chunk data.close() + self._adapter.close() def stream_upload(self, data, callback): """Generator for streaming request body data. diff --git a/ClientRuntimes/Python/msrest/msrest/version.py b/ClientRuntimes/Python/msrest/msrest/version.py index cb55186422823..11739ebc3606c 100644 --- a/ClientRuntimes/Python/msrest/msrest/version.py +++ b/ClientRuntimes/Python/msrest/msrest/version.py @@ -25,4 +25,4 @@ # -------------------------------------------------------------------------- -msrest_version = "0.1.3" +msrest_version = "0.2.0" diff --git a/ClientRuntimes/Python/msrest/readme.rst b/ClientRuntimes/Python/msrest/readme.rst index 0317e6b8a90b2..77e50e0da4bb2 100644 --- a/ClientRuntimes/Python/msrest/readme.rst +++ b/ClientRuntimes/Python/msrest/readme.rst @@ -15,6 +15,19 @@ To install: Release History --------------- +2016-03-25 Version 0.2.0 +++++++++++++++++++++++++ + +**Bugfixes** + +- Manage integer enum values (https://github.com/Azure/autorest/pull/879) +- Add missing application/json Accept HTTP header (https://github.com/Azure/azure-sdk-for-python/issues/553) + +**Beheviour changes** + +- Needs Autorest > 0.16.0 Nightly 20160324 + + 2016-03-21 Version 0.1.3 ++++++++++++++++++++++++ diff --git a/ClientRuntimes/Python/msrest/setup.py b/ClientRuntimes/Python/msrest/setup.py index 9db7f313040c3..b3dca9089b534 100644 --- a/ClientRuntimes/Python/msrest/setup.py +++ b/ClientRuntimes/Python/msrest/setup.py @@ -28,7 +28,7 @@ setup( name='msrest', - version='0.1.3', + version='0.2.0', author='Microsoft Corporation', packages=['msrest'], url=("https://github.com/xingwu1/autorest/tree/python/" diff --git a/ClientRuntimes/Python/msrest/test/unittest_runtime.py b/ClientRuntimes/Python/msrest/test/unittest_runtime.py index 7bb798d5af6d4..fbdad6791f772 100644 --- a/ClientRuntimes/Python/msrest/test/unittest_runtime.py +++ b/ClientRuntimes/Python/msrest/test/unittest_runtime.py @@ -101,7 +101,7 @@ def hook(aptr, req, *args, **kwargs): @mock.patch.object(requests, 'Session') def test_request_fail(self, mock_requests): - mock_requests.return_value.request.return_value = "test" + mock_requests.return_value.request.return_value = mock.Mock(_content_consumed=True) cfg = Configuration("https://my_service.com") creds = Authentication() @@ -113,7 +113,7 @@ def test_request_fail(self, mock_requests): check = httpretty.last_request() - self.assertEqual(response, "test") + self.assertTrue(response._content_consumed) mock_requests.return_value.request.side_effect = requests.RequestException with self.assertRaises(ClientRequestError): @@ -127,6 +127,8 @@ def test_request_proxy(self): def hook(adptr, request, *args, **kwargs): self.assertEqual(kwargs.get('proxies'), {"http://my_service.com":'http://localhost:57979'}) + kwargs['result']._content_consumed = True + kwargs['result'].status_code = 200 return kwargs['result'] client = ServiceClient(creds, cfg) @@ -139,6 +141,8 @@ def hook(adptr, request, *args, **kwargs): def hook2(adptr, request, *args, **kwargs): self.assertEqual(kwargs.get('proxies')['https'], "http://localhost:1987") + kwargs['result']._content_consumed = True + kwargs['result'].status_code = 200 return kwargs['result'] cfg = Configuration("http://my_service.com") diff --git a/ClientRuntimes/Python/msrestazure/doc/conf.py b/ClientRuntimes/Python/msrestazure/doc/conf.py index 4d22ad0992a90..9a76b3204d5c2 100644 --- a/ClientRuntimes/Python/msrestazure/doc/conf.py +++ b/ClientRuntimes/Python/msrestazure/doc/conf.py @@ -58,9 +58,9 @@ # built documents. # # The short X.Y version. -version = '0.1.2' +version = '0.2.1' # The full version, including alpha/beta/rc tags. -release = '0.1.2' +release = '0.2.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. diff --git a/ClientRuntimes/Python/msrestazure/msrestazure/azure_active_directory.py b/ClientRuntimes/Python/msrestazure/msrestazure/azure_active_directory.py index 74618d5a44131..80cbbb7fb5e23 100644 --- a/ClientRuntimes/Python/msrestazure/msrestazure/azure_active_directory.py +++ b/ClientRuntimes/Python/msrestazure/msrestazure/azure_active_directory.py @@ -416,7 +416,7 @@ def get_auth_url(self, msa=False, **additional_args): :param additional_args: Set and additional kwargs for requrired AAD configuration: msdn.microsoft.com/en-us/library/azure/dn645542.aspx :rtype: Tuple - :returns: The URL for authentication (str), and state code that will + :return: The URL for authentication (str), and state code that will be verified in the response (str). """ if msa: diff --git a/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py b/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py index 9f0c1729a56d4..0386b3a30b5cb 100644 --- a/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py +++ b/ClientRuntimes/Python/msrestazure/msrestazure/azure_operation.py @@ -31,7 +31,6 @@ except ImportError: from urllib.parse import urlparse -from msrest.pipeline import ClientRawResponse from msrest.exceptions import DeserializationError from msrestazure.azure_exceptions import CloudError @@ -42,14 +41,20 @@ def finished(status): + if hasattr(status, 'value'): + status = status.value return str(status).lower() in FINISHED def failed(status): + if hasattr(status, 'value'): + status = status.value return str(status).lower() in FAILED def succeeded(status): + if hasattr(status, 'value'): + status = status.value return str(status).lower() in SUCCEEDED @@ -130,12 +135,7 @@ def _deserialize(self, response): :raises: OperationFinished if deserialised resource has status succeeded. """ - resource = self.get_outputs(response) - if isinstance(resource, ClientRawResponse): - self.resource = resource.output - self.raw = resource - else: - self.resource = resource + self.resource = self.get_outputs(response) try: if failed(self.resource.provisioning_state): @@ -312,7 +312,6 @@ def __init__(self, response, outputs): self.get_outputs = outputs self.async_url = None self.location_url = None - self.raw = None def _check_status(self, response): """Check response status code is valid for a Put or Patch @@ -400,7 +399,6 @@ def __init__(self, response, outputs): self.get_outputs = outputs self.async_url = None self.location_url = None - self.raw = None def _check_status(self, response): """Check response status code is valid for a Put or Patch @@ -626,10 +624,7 @@ def result(self, timeout=None): :raises CloudError: Server problem with the query. """ self.wait(timeout) - if self._operation.raw: - return self._operation.raw - else: - return self._operation.resource + return self._operation.resource def wait(self, timeout=None): """Wait on the long running operation for a specified length diff --git a/ClientRuntimes/Python/msrestazure/msrestazure/version.py b/ClientRuntimes/Python/msrestazure/msrestazure/version.py index a0f21a3e502d4..23c80b2514da3 100644 --- a/ClientRuntimes/Python/msrestazure/msrestazure/version.py +++ b/ClientRuntimes/Python/msrestazure/msrestazure/version.py @@ -24,4 +24,4 @@ # # -------------------------------------------------------------------------- -msrestazure_version = "0.1.2" +msrestazure_version = "0.2.1" diff --git a/ClientRuntimes/Python/msrestazure/readme.rst b/ClientRuntimes/Python/msrestazure/readme.rst index 2241e5ce14619..18a49a8035f2b 100644 --- a/ClientRuntimes/Python/msrestazure/readme.rst +++ b/ClientRuntimes/Python/msrestazure/readme.rst @@ -15,6 +15,25 @@ To install: Release History --------------- +2016-03-31 Version 0.2.1 +++++++++++++++++++++++++ + +**Bugfixes** + +- Fix AzurePollerOperation if Swagger defines provisioning status as enum type (https://github.com/Azure/autorest/pull/892) + + +2016-03-25 Version 0.2.0 +++++++++++++++++++++++++ + +Update msrest dependency to 0.2.0 + +**Behaviour change** + +- async methods called with raw=True don't return anymore AzureOperationPoller but ClientRawResponse +- Needs Autorest > 0.16.0 Nightly 20160324 + + 2016-03-21 Version 0.1.2 ++++++++++++++++++++++++ diff --git a/ClientRuntimes/Python/msrestazure/requirements27.txt b/ClientRuntimes/Python/msrestazure/requirements27.txt index 26aa9d0fa73a6..4c6368baf850a 100644 --- a/ClientRuntimes/Python/msrestazure/requirements27.txt +++ b/ClientRuntimes/Python/msrestazure/requirements27.txt @@ -12,4 +12,4 @@ requests==2.7.0 requests-oauthlib==0.5.0 six==1.10.0 chardet==2.3.0 -msrest==0.1.1 +msrest==0.2.0 diff --git a/ClientRuntimes/Python/msrestazure/requirements35.txt b/ClientRuntimes/Python/msrestazure/requirements35.txt index e400edf782878..76fe44ba95f1c 100644 --- a/ClientRuntimes/Python/msrestazure/requirements35.txt +++ b/ClientRuntimes/Python/msrestazure/requirements35.txt @@ -10,4 +10,4 @@ requests==2.7.0 requests-oauthlib==0.5.0 six==1.10.0 chardet==2.3.0 -msrest==0.1.1 +msrest==0.2.0 diff --git a/ClientRuntimes/Python/msrestazure/setup.py b/ClientRuntimes/Python/msrestazure/setup.py index d723f963d1d0b..d25ce47f33493 100644 --- a/ClientRuntimes/Python/msrestazure/setup.py +++ b/ClientRuntimes/Python/msrestazure/setup.py @@ -28,7 +28,7 @@ setup( name='msrestazure', - version='0.1.2', + version='0.2.1', author='Microsoft Corporation', packages=['msrestazure'], url=('https://github.com/xingwu1/autorest/tree/python/' @@ -49,5 +49,5 @@ 'License :: OSI Approved :: MIT License', 'Topic :: Software Development'], install_requires=[ - "msrest>=0.1.3"], + "msrest>=0.2.0"], ) diff --git a/Documentation/swagger-extensions.md b/Documentation/swagger-extensions.md index cef0b89a0c3d4..1fbf0efe46d71 100644 --- a/Documentation/swagger-extensions.md +++ b/Documentation/swagger-extensions.md @@ -385,16 +385,23 @@ When used, replaces the standard Swagger "host" attribute with a host that conta **Parent element**: [Info Object](https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#infoObject) **Schema**: + Field Name | Type | Description ---|:---:|--- hostTemplate | `string` | **Required**. Specifies the parameterized template for the host. -parameters | [Array of Parameter Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject) | The list of parameters that are used within the hostTemplate. This can include both reference parameters as well as explicit parameters. Note that "in" is **required** and **must be** set to "path" +useSchemePrefix | `boolean` | **Optional, Default: true**. Specifes whether to prepend the default scheme a.k.a protocol to the base uri of client. +positionInOperation | `string` | **Optional, Default: first**. Specifies whether the list of parameters will appear in the beginning or in the end, in the method signature for every operation. The order within the parameters provided in the below mentioned array will be preserved. Either the array of parameters will be prepended or appended, based on the value provided over here. Valid values are **"first", "last"**. Every method/operation in any programming language has parameters categorized into two buckets **"required"** and **"optional"**. It is natural for optional paramaters to appear in the end in a method signature. **This aspect will be preserved, while prepending(first) or appending(last) hostTemplate parameters .** +parameters | [Array of Parameter Objects](https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#parameterObject) | The list of parameters that are used within the hostTemplate. This can include both reference parameters as well as explicit parameters. Note that "in" is **required** and **must be** set to **"path"**. The reference parameters will be treated as **global parameters** and will end up as property of the client. **Example**: -Using both explicit and reference parameters +- Using both explicit and reference parameters. + - Since "useSchemePrefix" is not specified, it's default value true will be applied. The user is expected to provide only the value of accountName. The generated code will fit it as a part of the url. + - Since "positionInOperation" with value "last" is specified, "accountName" will be the last required parameter in every method. "adlaJobDnsSuffixInPath" will be a property on the client as it is defined in the global parameters section and is referenced here. + ```js "x-ms-parameterized-host": { "hostTemplate": "{accountName}.{adlaJobDnsSuffix}", + "positionInOperation": "last", "parameters": [ { "name": "accountName", @@ -420,10 +427,13 @@ Using both explicit and reference parameters "description": "Gets the DNS suffix used as the base for all Azure Data Lake Analytics Job service requests." } ``` -Using only explicit parameters +- Using explicit parameters and specifying the positionInOperation and schemePrefix. + - This means that accountName will be the first required parameter in all the methods and the user is expected to provide a url (protocol + accountName), since "useSchemePrfix" is set to false. ```js "x-ms-parameterized-host": { "hostTemplate": "{accountName}.mystaticsuffix.com", + "useSchemePrefix": false, + "positionInOperation": "first", "parameters": [ { "name": "accountName", @@ -463,7 +473,7 @@ The REST API guidelines define a common pattern for paging through lists of data Field Name | Type | Description ---|:---:|--- -nextLinkName| `string` | Specifies the name of the property that provides the nextLink. If the model does not have the nextLink property then specify null. +nextLinkName| `string` | Specifies the name of the property that provides the nextLink. **If the model does not have the nextLink property then specify null. This will be useful for the services that return an object that has an array referenced by the itemName. The object is flattened in a way that the array is directly returned. Since the nextLinkName is explicitly specified to null, the generated code will not implement paging. However, you get the benefit of flattening. Thus providing a better client side API to the end user.** itemName | `string` | Specifies the name of the property that provides the collection of pageable items. Default value is 'value'.{Postfix}`. operationName | `string` | Specifies the name of the Next operation. Default value is 'XXXNext' where XXX is the name of the operation @@ -595,4 +605,4 @@ When set, specifies the header parameter to be used instead of `x-ms-client-requ } } } -``` \ No newline at end of file +``` diff --git a/Samples/azure-storage/Azure.CSharp/StorageAccountsOperations.cs b/Samples/azure-storage/Azure.CSharp/StorageAccountsOperations.cs index 315e390de4e46..1b1c5f06a3e5c 100644 --- a/Samples/azure-storage/Azure.CSharp/StorageAccountsOperations.cs +++ b/Samples/azure-storage/Azure.CSharp/StorageAccountsOperations.cs @@ -133,9 +133,12 @@ internal StorageAccountsOperations(StorageManagementClient client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(accountName, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(accountName != null) + { + _requestContent = SafeJsonConvert.SerializeObject(accountName, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -381,9 +384,12 @@ internal StorageAccountsOperations(StorageManagementClient client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(parameters != null) + { + _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -960,9 +966,12 @@ internal StorageAccountsOperations(StorageManagementClient client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(parameters != null) + { + _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { @@ -1704,9 +1713,12 @@ internal StorageAccountsOperations(StorageManagementClient client) // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(regenerateKey, this.Client.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(regenerateKey != null) + { + _requestContent = SafeJsonConvert.SerializeObject(regenerateKey, this.Client.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Set Credentials if (this.Client.Credentials != null) { diff --git a/Samples/azure-storage/Azure.Java/models/AccountStatus.java b/Samples/azure-storage/Azure.Java/models/AccountStatus.java index 616292abb7d72..935263fada2a2 100644 --- a/Samples/azure-storage/Azure.Java/models/AccountStatus.java +++ b/Samples/azure-storage/Azure.Java/models/AccountStatus.java @@ -49,4 +49,9 @@ public static AccountStatus fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Java/models/AccountType.java b/Samples/azure-storage/Azure.Java/models/AccountType.java index 2cbd46baf78cd..8eb41907b7c13 100644 --- a/Samples/azure-storage/Azure.Java/models/AccountType.java +++ b/Samples/azure-storage/Azure.Java/models/AccountType.java @@ -58,4 +58,9 @@ public static AccountType fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Java/models/ProvisioningState.java b/Samples/azure-storage/Azure.Java/models/ProvisioningState.java index 1a60a0a9b4fc5..e3c51eac5efb4 100644 --- a/Samples/azure-storage/Azure.Java/models/ProvisioningState.java +++ b/Samples/azure-storage/Azure.Java/models/ProvisioningState.java @@ -52,4 +52,9 @@ public static ProvisioningState fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Java/models/Reason.java b/Samples/azure-storage/Azure.Java/models/Reason.java index e67cd8258a95a..d281c844c5058 100644 --- a/Samples/azure-storage/Azure.Java/models/Reason.java +++ b/Samples/azure-storage/Azure.Java/models/Reason.java @@ -49,4 +49,9 @@ public static Reason fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Java/models/StorageAccountCreateParameters.java b/Samples/azure-storage/Azure.Java/models/StorageAccountCreateParameters.java index 8f8c249d078a6..975c17e4c375e 100644 --- a/Samples/azure-storage/Azure.Java/models/StorageAccountCreateParameters.java +++ b/Samples/azure-storage/Azure.Java/models/StorageAccountCreateParameters.java @@ -3,8 +3,8 @@ package petstore.models; -import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The parameters to provide for the account. diff --git a/Samples/azure-storage/Azure.Java/models/UsageUnit.java b/Samples/azure-storage/Azure.Java/models/UsageUnit.java index f9ffb8b0fce07..1996e58717476 100644 --- a/Samples/azure-storage/Azure.Java/models/UsageUnit.java +++ b/Samples/azure-storage/Azure.Java/models/UsageUnit.java @@ -61,4 +61,9 @@ public static UsageUnit fromValue(String value) { } return null; } + + @Override + public String toString() { + return toValue(); + } } diff --git a/Samples/azure-storage/Azure.Python/setup.py b/Samples/azure-storage/Azure.Python/setup.py index f3539db2972f1..b9fe5db7a8f35 100644 --- a/Samples/azure-storage/Azure.Python/setup.py +++ b/Samples/azure-storage/Azure.Python/setup.py @@ -15,7 +15,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0", "msrestazure>=0.1.0"] +REQUIRES = ["msrest>=0.2.0", "msrestazure>=0.2.1"] setup( name=NAME, diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/check_name_availability_result.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/check_name_availability_result.py index 0bbc5f5c291e2..1c7ee5c86a0b9 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/check_name_availability_result.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/check_name_availability_result.py @@ -28,7 +28,7 @@ class CheckNameAvailabilityResult(Model): 'message': {'key': 'message', 'type': 'str'}, } - def __init__(self, name_available=None, reason=None, message=None, **kwargs): + def __init__(self, name_available=None, reason=None, message=None): self.name_available = name_available self.reason = reason self.message = message diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/custom_domain.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/custom_domain.py index ee95d5f7d6163..77a0857f912e8 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/custom_domain.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/custom_domain.py @@ -27,6 +27,6 @@ class CustomDomain(Model): 'use_sub_domain': {'key': 'useSubDomain', 'type': 'bool'}, } - def __init__(self, name, use_sub_domain=None, **kwargs): + def __init__(self, name, use_sub_domain=None): self.name = name self.use_sub_domain = use_sub_domain diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/endpoints.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/endpoints.py index de3d2386cd0a1..155622f51543c 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/endpoints.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/endpoints.py @@ -27,7 +27,7 @@ class Endpoints(Model): 'file': {'key': 'file', 'type': 'str'}, } - def __init__(self, blob=None, queue=None, table=None, file=None, **kwargs): + def __init__(self, blob=None, queue=None, table=None, file=None): self.blob = blob self.queue = queue self.table = table diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py index 0bcb8add022c5..87763cb25e4b4 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/resource.py @@ -8,18 +8,27 @@ class Resource(Model): """Resource - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags :type tags: dict """ + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, @@ -28,9 +37,9 @@ class Resource(Model): 'tags': {'key': 'tags', 'type': '{str}'}, } - def __init__(self, id=None, name=None, type=None, location=None, tags=None, **kwargs): - self.id = id - self.name = name - self.type = type + def __init__(self, location=None, tags=None): + self.id = None + self.name = None + self.type = None self.location = location self.tags = tags diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py index 3949fa133fb15..1aeaa6bc9f22d 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account.py @@ -9,12 +9,15 @@ class StorageAccount(Resource): """ The storage account. - :param id: Resource Id - :type id: str - :param name: Resource name - :type name: str - :param type: Resource type - :type type: str + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: Resource Id + :vartype id: str + :ivar name: Resource name + :vartype name: str + :ivar type: Resource type + :vartype type: str :param location: Resource location :type location: str :param tags: Resource tags @@ -24,6 +27,12 @@ class StorageAccount(Resource): ` """ + _validation = { + 'id': {'readonly': True}, + 'name': {'readonly': True}, + 'type': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, @@ -33,6 +42,6 @@ class StorageAccount(Resource): 'properties': {'key': 'properties', 'type': 'StorageAccountProperties'}, } - def __init__(self, id=None, name=None, type=None, location=None, tags=None, properties=None, **kwargs): - super(StorageAccount, self).__init__(id=id, name=name, type=type, location=location, tags=tags, **kwargs) + def __init__(self, location=None, tags=None, properties=None): + super(StorageAccount, self).__init__(location=location, tags=tags) self.properties = properties diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_check_name_availability_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_check_name_availability_parameters.py index 2ee4a450e04a8..bca58a1d79bab 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_check_name_availability_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_check_name_availability_parameters.py @@ -23,6 +23,6 @@ class StorageAccountCheckNameAvailabilityParameters(Model): 'type': {'key': 'type', 'type': 'str'}, } - def __init__(self, name, type="Microsoft.Storage/storageAccounts", **kwargs): + def __init__(self, name, type="Microsoft.Storage/storageAccounts"): self.name = name self.type = type diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_create_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_create_parameters.py index d490562665d8b..1f5fe04cca5bc 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_create_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_create_parameters.py @@ -28,7 +28,7 @@ class StorageAccountCreateParameters(Model): 'properties': {'key': 'properties', 'type': 'StorageAccountPropertiesCreateParameters'}, } - def __init__(self, location, tags=None, properties=None, **kwargs): + def __init__(self, location, tags=None, properties=None): self.location = location self.tags = tags self.properties = properties diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_keys.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_keys.py index 3bc0943541fc0..171d1d785f012 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_keys.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_keys.py @@ -20,6 +20,6 @@ class StorageAccountKeys(Model): 'key2': {'key': 'key2', 'type': 'str'}, } - def __init__(self, key1=None, key2=None, **kwargs): + def __init__(self, key1=None, key2=None): self.key1 = key1 self.key2 = key2 diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties.py index cb58445a1ce39..2259b66353acf 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties.py @@ -69,7 +69,7 @@ class StorageAccountProperties(Model): 'secondary_endpoints': {'key': 'secondaryEndpoints', 'type': 'Endpoints'}, } - def __init__(self, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None, **kwargs): + def __init__(self, provisioning_state=None, account_type=None, primary_endpoints=None, primary_location=None, status_of_primary=None, last_geo_failover_time=None, secondary_location=None, status_of_secondary=None, creation_time=None, custom_domain=None, secondary_endpoints=None): self.provisioning_state = provisioning_state self.account_type = account_type self.primary_endpoints = primary_endpoints diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_create_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_create_parameters.py index 4d69da5caf759..b2d63195ed800 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_create_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_create_parameters.py @@ -22,5 +22,5 @@ class StorageAccountPropertiesCreateParameters(Model): 'account_type': {'key': 'accountType', 'type': 'AccountType'}, } - def __init__(self, account_type, **kwargs): + def __init__(self, account_type): self.account_type = account_type diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_update_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_update_parameters.py index 9a5fbc12e1783..a9a27ddebd2c1 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_update_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_properties_update_parameters.py @@ -26,6 +26,6 @@ class StorageAccountPropertiesUpdateParameters(Model): 'custom_domain': {'key': 'customDomain', 'type': 'CustomDomain'}, } - def __init__(self, account_type=None, custom_domain=None, **kwargs): + def __init__(self, account_type=None, custom_domain=None): self.account_type = account_type self.custom_domain = custom_domain diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_regenerate_key_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_regenerate_key_parameters.py index 04c4ce47cf68b..057ea3a49177e 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_regenerate_key_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_regenerate_key_parameters.py @@ -20,5 +20,5 @@ class StorageAccountRegenerateKeyParameters(Model): 'key_name': {'key': 'keyName', 'type': 'str'}, } - def __init__(self, key_name, **kwargs): + def __init__(self, key_name): self.key_name = key_name diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_update_parameters.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_update_parameters.py index f339b37d57d36..39c5cd78d1599 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_update_parameters.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/storage_account_update_parameters.py @@ -21,6 +21,6 @@ class StorageAccountUpdateParameters(Model): 'properties': {'key': 'properties', 'type': 'StorageAccountPropertiesUpdateParameters'}, } - def __init__(self, tags=None, properties=None, **kwargs): + def __init__(self, tags=None, properties=None): self.tags = tags self.properties = properties diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage.py index aa81987351d9c..a22a532456d2c 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage.py @@ -37,7 +37,7 @@ class Usage(Model): 'name': {'key': 'name', 'type': 'UsageName'}, } - def __init__(self, unit, current_value, limit, name, **kwargs): + def __init__(self, unit, current_value, limit, name): self.unit = unit self.current_value = current_value self.limit = limit diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage_name.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage_name.py index 3477988bfbb5c..5edfc23c328e0 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage_name.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/models/usage_name.py @@ -21,6 +21,6 @@ class UsageName(Model): 'localized_value': {'key': 'localizedValue', 'type': 'str'}, } - def __init__(self, value=None, localized_value=None, **kwargs): + def __init__(self, value=None, localized_value=None): self.value = value self.localized_value = localized_value diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/operations/storage_accounts_operations.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/operations/storage_accounts_operations.py index 37991304faeee..ef19c00fbeeac 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/operations/storage_accounts_operations.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/operations/storage_accounts_operations.py @@ -117,14 +117,12 @@ def create( :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response - :param operation_config: :ref:`Operation configuration - overrides`. :rtype: :class:`AzureOperationPoller` - :return: A poller object which can return :class:`StorageAccount - ` or - :class:`ClientRawResponse` if - raw=true + instance that returns :class:`StorageAccount + ` + :rtype: :class:`ClientRawResponse` + if raw=true """ # Construct URL url = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' @@ -184,6 +182,10 @@ def get_long_running_output(response): return deserialized + if raw: + response = long_running_send() + return get_long_running_output(response) + long_running_operation_timeout = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) diff --git a/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py b/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py index 732eb30e70fb2..00031c87fca75 100644 --- a/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py +++ b/Samples/azure-storage/Azure.Python/storagemanagementclient/storage_management_client.py @@ -43,9 +43,15 @@ def __init__( self, credentials, subscription_id, api_version='2015-06-15', accept_language='en-US', long_running_operation_retry_timeout=30, generate_client_request_id=True, base_url=None, filepath=None): if credentials is None: - raise ValueError('credentials must not be None.') + raise ValueError("Parameter 'credentials' must not be None.") if subscription_id is None: - raise ValueError('subscription_id must not be None.') + raise ValueError("Parameter 'subscription_id' must not be None.") + if not isinstance(subscription_id, str): + raise TypeError("Parameter 'subscription_id' must be str.") + if api_version is not None and not isinstance(api_version, str): + raise TypeError("Optional parameter 'api_version' must be str.") + if accept_language is not None and not isinstance(accept_language, str): + raise TypeError("Optional parameter 'accept_language' must be str.") if not base_url: base_url = 'https://management.azure.com' diff --git a/Samples/azure-storage/Azure.Ruby/azure_storage/storage_accounts.rb b/Samples/azure-storage/Azure.Ruby/azure_storage/storage_accounts.rb index 72caad2e4c328..d81d3ec1045df 100644 --- a/Samples/azure-storage/Azure.Ruby/azure_storage/storage_accounts.rb +++ b/Samples/azure-storage/Azure.Ruby/azure_storage/storage_accounts.rb @@ -80,7 +80,7 @@ def check_name_availability_async(account_name, custom_headers = nil) unless account_name.nil? account_name = StorageAccountCheckNameAvailabilityParameters.serialize_object(account_name) end - request_content = JSON.generate(account_name, quirks_mode: true) + request_content = account_name != nil ? JSON.generate(account_name, quirks_mode: true) : nil path_template = '/subscriptions/{subscriptionId}/providers/Microsoft.Storage/checkNameAvailability' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -251,7 +251,7 @@ def begin_create_async(resource_group_name, account_name, parameters, custom_hea unless parameters.nil? parameters = StorageAccountCreateParameters.serialize_object(parameters) end - request_content = JSON.generate(parameters, quirks_mode: true) + request_content = parameters != nil ? JSON.generate(parameters, quirks_mode: true) : nil path_template = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -596,7 +596,7 @@ def update_async(resource_group_name, account_name, parameters, custom_headers = unless parameters.nil? parameters = StorageAccountUpdateParameters.serialize_object(parameters) end - request_content = JSON.generate(parameters, quirks_mode: true) + request_content = parameters != nil ? JSON.generate(parameters, quirks_mode: true) : nil path_template = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -985,7 +985,7 @@ def regenerate_key_async(resource_group_name, account_name, regenerate_key, cust unless regenerate_key.nil? regenerate_key = StorageAccountRegenerateKeyParameters.serialize_object(regenerate_key) end - request_content = JSON.generate(regenerate_key, quirks_mode: true) + request_content = regenerate_key != nil ? JSON.generate(regenerate_key, quirks_mode: true) : nil path_template = '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/regenerateKey' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], diff --git a/Samples/petstore/CSharp/SwaggerPetstore.cs b/Samples/petstore/CSharp/SwaggerPetstore.cs index 89e8e3e8158f8..7d157b55636fc 100644 --- a/Samples/petstore/CSharp/SwaggerPetstore.cs +++ b/Samples/petstore/CSharp/SwaggerPetstore.cs @@ -194,9 +194,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -294,9 +297,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -394,9 +400,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1415,9 +1424,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1748,9 +1760,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1844,9 +1859,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -1940,9 +1958,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { @@ -2379,9 +2400,12 @@ private void Initialize() // Serialize Request string _requestContent = null; - _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); - _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); - _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + if(body != null) + { + _requestContent = SafeJsonConvert.SerializeObject(body, this.SerializationSettings); + _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); + _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); + } // Send Request if (_shouldTrace) { diff --git a/Samples/petstore/Java/SwaggerPetstore.java b/Samples/petstore/Java/SwaggerPetstore.java index 1b275e1d5217d..627abbb4152ed 100644 --- a/Samples/petstore/Java/SwaggerPetstore.java +++ b/Samples/petstore/Java/SwaggerPetstore.java @@ -12,8 +12,6 @@ import com.microsoft.rest.ServiceCallback; import com.microsoft.rest.ServiceException; import com.microsoft.rest.ServiceResponse; -import java.io.File; -import java.io.InputStream; import java.io.IOException; import java.util.Map; import petstore.models.Order; @@ -405,7 +403,7 @@ public interface SwaggerPetstore { * @throws IOException exception thrown from serialization/deserialization * @return the {@link ServiceResponse} object if successful. */ - ServiceResponse uploadFile(long petId, String additionalMetadata, File file) throws ServiceException, IOException; + ServiceResponse uploadFile(long petId, String additionalMetadata, byte[] file) throws ServiceException, IOException; /** * uploads an image. @@ -417,7 +415,7 @@ public interface SwaggerPetstore { * @throws IllegalArgumentException thrown if callback is null * @return the {@link ServiceCall} object */ - ServiceCall uploadFileAsync(long petId, String additionalMetadata, File file, final ServiceCallback serviceCallback) throws IllegalArgumentException; + ServiceCall uploadFileAsync(long petId, String additionalMetadata, byte[] file, final ServiceCallback serviceCallback) throws IllegalArgumentException; /** * Returns pet inventories by status. diff --git a/Samples/petstore/Java/SwaggerPetstoreImpl.java b/Samples/petstore/Java/SwaggerPetstoreImpl.java index 654134d24740b..0a5af09be4725 100644 --- a/Samples/petstore/Java/SwaggerPetstoreImpl.java +++ b/Samples/petstore/Java/SwaggerPetstoreImpl.java @@ -17,13 +17,10 @@ import com.microsoft.rest.ServiceResponseBuilder; import com.microsoft.rest.ServiceResponseCallback; import com.microsoft.rest.Validator; -import java.io.File; import java.io.InputStream; import java.io.IOException; import java.util.List; import java.util.Map; -import okhttp3.MediaType; -import okhttp3.RequestBody; import okhttp3.ResponseBody; import petstore.models.Order; import petstore.models.Pet; @@ -487,8 +484,8 @@ private ServiceResponse updatePetDelegate(Response response) * @return the List<Pet> object wrapped in {@link ServiceResponse} if successful. */ public ServiceResponse> findPetsByStatus() throws ServiceException, IOException { - final List status = null; - Call call = service.findPetsByStatus(this.getMapperAdapter().serializeList(status, CollectionFormat.CSV)); + final String statusConverted = null; + Call call = service.findPetsByStatus(statusConverted); return findPetsByStatusDelegate(call.execute()); } @@ -504,8 +501,8 @@ public ServiceCall findPetsByStatusAsync(final ServiceCallback> servic if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List status = null; - Call call = service.findPetsByStatus(this.getMapperAdapter().serializeList(status, CollectionFormat.CSV)); + final String statusConverted = null; + Call call = service.findPetsByStatus(statusConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -531,7 +528,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse> findPetsByStatus(List status) throws ServiceException, IOException { Validator.validate(status); - Call call = service.findPetsByStatus(this.getMapperAdapter().serializeList(status, CollectionFormat.CSV)); + String statusConverted = this.getMapperAdapter().serializeList(status, CollectionFormat.CSV); + Call call = service.findPetsByStatus(statusConverted); return findPetsByStatusDelegate(call.execute()); } @@ -549,7 +547,8 @@ public ServiceCall findPetsByStatusAsync(List status, final ServiceCallb throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(status, serviceCallback); - Call call = service.findPetsByStatus(this.getMapperAdapter().serializeList(status, CollectionFormat.CSV)); + String statusConverted = this.getMapperAdapter().serializeList(status, CollectionFormat.CSV); + Call call = service.findPetsByStatus(statusConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -580,8 +579,8 @@ private ServiceResponse> findPetsByStatusDelegate(Response> findPetsByTags() throws ServiceException, IOException { - final List tags = null; - Call call = service.findPetsByTags(this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV)); + final String tagsConverted = null; + Call call = service.findPetsByTags(tagsConverted); return findPetsByTagsDelegate(call.execute()); } @@ -597,8 +596,8 @@ public ServiceCall findPetsByTagsAsync(final ServiceCallback> serviceC if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - final List tags = null; - Call call = service.findPetsByTags(this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV)); + final String tagsConverted = null; + Call call = service.findPetsByTags(tagsConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -624,7 +623,8 @@ public void onResponse(Call call, Response response) */ public ServiceResponse> findPetsByTags(List tags) throws ServiceException, IOException { Validator.validate(tags); - Call call = service.findPetsByTags(this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV)); + String tagsConverted = this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV); + Call call = service.findPetsByTags(tagsConverted); return findPetsByTagsDelegate(call.execute()); } @@ -642,7 +642,8 @@ public ServiceCall findPetsByTagsAsync(List tags, final ServiceCallback< throw new IllegalArgumentException("ServiceCallback is required for async calls."); } Validator.validate(tags, serviceCallback); - Call call = service.findPetsByTags(this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV)); + String tagsConverted = this.getMapperAdapter().serializeList(tags, CollectionFormat.CSV); + Call call = service.findPetsByTags(tagsConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback>(serviceCallback) { @Override @@ -974,8 +975,8 @@ private ServiceResponse deletePetDelegate(Response response) */ public ServiceResponse uploadFile(long petId) throws ServiceException, IOException { final String additionalMetadata = null; - final InputStream file = null; - Call call = service.uploadFile(petId, additionalMetadata, RequestBody.create(MediaType.parse("multipart/form-data"), file)); + final RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), new byte[0]); + Call call = service.uploadFile(petId, additionalMetadata, fileConverted); return uploadFileDelegate(call.execute()); } @@ -992,8 +993,8 @@ public ServiceCall uploadFileAsync(long petId, final ServiceCallback servi throw new IllegalArgumentException("ServiceCallback is required for async calls."); } final String additionalMetadata = null; - final InputStream file = null; - Call call = service.uploadFile(petId, additionalMetadata, RequestBody.create(MediaType.parse("multipart/form-data"), file)); + final RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), new byte[0]); + Call call = service.uploadFile(petId, additionalMetadata, fileConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override @@ -1018,8 +1019,12 @@ public void onResponse(Call call, Response response) * @throws IOException exception thrown from serialization/deserialization * @return the {@link ServiceResponse} object if successful. */ - public ServiceResponse uploadFile(long petId, String additionalMetadata, File file) throws ServiceException, IOException { - Call call = service.uploadFile(petId, additionalMetadata, RequestBody.create(MediaType.parse("multipart/form-data"), file)); + public ServiceResponse uploadFile(long petId, String additionalMetadata, byte[] file) throws ServiceException, IOException { + RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), new byte[0]); + if (file != null) { + fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + } + Call call = service.uploadFile(petId, additionalMetadata, fileConverted); return uploadFileDelegate(call.execute()); } @@ -1033,11 +1038,15 @@ public ServiceResponse uploadFile(long petId, String additionalMetadata, F * @throws IllegalArgumentException thrown if callback is null * @return the {@link Call} object */ - public ServiceCall uploadFileAsync(long petId, String additionalMetadata, File file, final ServiceCallback serviceCallback) throws IllegalArgumentException { + public ServiceCall uploadFileAsync(long petId, String additionalMetadata, byte[] file, final ServiceCallback serviceCallback) throws IllegalArgumentException { if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - Call call = service.uploadFile(petId, additionalMetadata, RequestBody.create(MediaType.parse("multipart/form-data"), file)); + RequestBody fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), new byte[0]); + if (file != null) { + fileConverted = RequestBody.create(MediaType.parse("multipart/form-data"), file); + } + Call call = service.uploadFile(petId, additionalMetadata, fileConverted); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @Override diff --git a/Samples/petstore/Java/models/Order.java b/Samples/petstore/Java/models/Order.java index c0cf41ebe32c0..6a884a05c294b 100644 --- a/Samples/petstore/Java/models/Order.java +++ b/Samples/petstore/Java/models/Order.java @@ -3,8 +3,8 @@ package petstore.models; -import com.fasterxml.jackson.annotation.JsonProperty; import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The Order model. diff --git a/Samples/petstore/Java/models/Pet.java b/Samples/petstore/Java/models/Pet.java index 588445cd7a54f..1e172fcfe73f3 100644 --- a/Samples/petstore/Java/models/Pet.java +++ b/Samples/petstore/Java/models/Pet.java @@ -3,8 +3,8 @@ package petstore.models; -import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; /** * The Pet model. diff --git a/Samples/petstore/Python/setup.py b/Samples/petstore/Python/setup.py index f1c57ff21b2c6..bd6e6ed040665 100644 --- a/Samples/petstore/Python/setup.py +++ b/Samples/petstore/Python/setup.py @@ -15,7 +15,7 @@ # prerequisite: setuptools # http://pypi.python.org/pypi/setuptools -REQUIRES = ["msrest>=0.1.0"] +REQUIRES = ["msrest>=0.2.0"] setup( name=NAME, diff --git a/Samples/petstore/Python/swaggerpetstore/models/category.py b/Samples/petstore/Python/swaggerpetstore/models/category.py index 274c76da920e0..70aae7c8f0d90 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/category.py +++ b/Samples/petstore/Python/swaggerpetstore/models/category.py @@ -19,6 +19,6 @@ class Category(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/Samples/petstore/Python/swaggerpetstore/models/order.py b/Samples/petstore/Python/swaggerpetstore/models/order.py index e02faeb1811a7..6e1f3c0aac504 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/order.py +++ b/Samples/petstore/Python/swaggerpetstore/models/order.py @@ -8,8 +8,11 @@ class Order(Model): """Order - :param id: - :type id: long + Variables are only populated by the server, and will be ignored when + sending a request. + + :ivar id: + :vartype id: long :param pet_id: :type pet_id: long :param quantity: @@ -23,6 +26,10 @@ class Order(Model): :type complete: bool """ + _validation = { + 'id': {'readonly': True}, + } + _attribute_map = { 'id': {'key': 'id', 'type': 'long'}, 'pet_id': {'key': 'petId', 'type': 'long'}, @@ -32,8 +39,8 @@ class Order(Model): 'complete': {'key': 'complete', 'type': 'bool'}, } - def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=None, **kwargs): - self.id = id + def __init__(self, pet_id=None, quantity=None, ship_date=None, status=None, complete=None): + self.id = None self.pet_id = pet_id self.quantity = quantity self.ship_date = ship_date diff --git a/Samples/petstore/Python/swaggerpetstore/models/pet.py b/Samples/petstore/Python/swaggerpetstore/models/pet.py index eea3cb945d5af..3c01b6a3ba08d 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/pet.py +++ b/Samples/petstore/Python/swaggerpetstore/models/pet.py @@ -37,7 +37,7 @@ class Pet(Model): 'status': {'key': 'status', 'type': 'str'}, } - def __init__(self, name, photo_urls, id=None, category=None, tags=None, status=None, **kwargs): + def __init__(self, name, photo_urls, id=None, category=None, tags=None, status=None): self.id = id self.category = category self.name = name diff --git a/Samples/petstore/Python/swaggerpetstore/models/tag.py b/Samples/petstore/Python/swaggerpetstore/models/tag.py index 34b6460af1321..38d4ffbabcd1f 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/tag.py +++ b/Samples/petstore/Python/swaggerpetstore/models/tag.py @@ -19,6 +19,6 @@ class Tag(Model): 'name': {'key': 'name', 'type': 'str'}, } - def __init__(self, id=None, name=None, **kwargs): + def __init__(self, id=None, name=None): self.id = id self.name = name diff --git a/Samples/petstore/Python/swaggerpetstore/models/user.py b/Samples/petstore/Python/swaggerpetstore/models/user.py index ce6eeadc63758..17d843abff65b 100644 --- a/Samples/petstore/Python/swaggerpetstore/models/user.py +++ b/Samples/petstore/Python/swaggerpetstore/models/user.py @@ -37,7 +37,7 @@ class User(Model): 'user_status': {'key': 'userStatus', 'type': 'int'}, } - def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None, **kwargs): + def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): self.id = id self.username = username self.first_name = first_name diff --git a/Samples/petstore/Ruby/petstore/swagger_petstore.rb b/Samples/petstore/Ruby/petstore/swagger_petstore.rb index ba3ac332575a2..9584898cad19a 100644 --- a/Samples/petstore/Ruby/petstore/swagger_petstore.rb +++ b/Samples/petstore/Ruby/petstore/swagger_petstore.rb @@ -68,7 +68,7 @@ def add_pet_using_byte_array_async(body = nil, custom_headers = nil) # Serialize Request request_headers['Content-Type'] = 'application/json; charset=utf-8' - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/pet' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -141,7 +141,7 @@ def add_pet_async(body = nil, custom_headers = nil) unless body.nil? body = Pet.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/pet' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -214,7 +214,7 @@ def update_pet_async(body = nil, custom_headers = nil) unless body.nil? body = Pet.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/pet' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -950,7 +950,7 @@ def place_order_async(body = nil, custom_headers = nil) unless body.nil? body = Order.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/store/order' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -1204,7 +1204,7 @@ def create_user_async(body = nil, custom_headers = nil) unless body.nil? body = User.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/user' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -1284,7 +1284,7 @@ def create_users_with_array_input_async(body = nil, custom_headers = nil) end body = serializedArray end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/user/createWithArray' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -1364,7 +1364,7 @@ def create_users_with_list_input_async(body = nil, custom_headers = nil) end body = serializedArray end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/user/createWithList' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], @@ -1668,7 +1668,7 @@ def update_user_async(username, body = nil, custom_headers = nil) unless body.nil? body = User.serialize_object(body) end - request_content = JSON.generate(body, quirks_mode: true) + request_content = body != nil ? JSON.generate(body, quirks_mode: true) : nil path_template = '/user/{username}' options = { middlewares: [[MsRest::RetryPolicyMiddleware, times: 3, retry: 0.02], [:cookie_jar]], diff --git a/gulpfile.js b/gulpfile.js index 46785dfa21046..e7bc6be0adf4a 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -63,7 +63,8 @@ var defaultMappings = { 'AcceptanceTests/Url': '../../../TestServer/swagger/url.json', 'AcceptanceTests/Validation': '../../../TestServer/swagger/validation.json', 'AcceptanceTests/CustomBaseUri': '../../../TestServer/swagger/custom-baseUrl.json', - 'AcceptanceTests/ModelFlattening': '../../../TestServer/swagger/model-flattening.json', + 'AcceptanceTests/CustomBaseUriMoreOptions': '../../../TestServer/swagger/custom-baseUrl-more-options.json', + 'AcceptanceTests/ModelFlattening': '../../../TestServer/swagger/model-flattening.json' }; var rubyMappings = { @@ -411,13 +412,23 @@ gulp.task('regenerate:expected:samples:azure', function(){ } }); +var msBuildToolsVersion = 12.0; +if (isWindows) { + fs.readdirSync('C:/Program Files (x86)/MSBuild/').forEach(function (item) { + var itemAsFloat = parseFloat(item); + if (itemAsFloat > msBuildToolsVersion) { + msBuildToolsVersion = itemAsFloat; + } + }); +} + var msbuildDefaults = { stdout: process.stdout, stderr: process.stderr, maxBuffer: MAX_BUFFER, verbosity: 'minimal', errorOnFail: true, - toolsVersion: 12.0 + toolsVersion: msBuildToolsVersion }; gulp.task('clean:node_modules', function(cb) { diff --git a/schema/swagger-extensions.json b/schema/swagger-extensions.json index d00484f12ab88..6e6476c56dbf0 100644 --- a/schema/swagger-extensions.json +++ b/schema/swagger-extensions.json @@ -65,10 +65,10 @@ "$ref": "#/definitions/responseDefinitions" }, "security": { - "$ref": "#/definitions/security" + "$ref": "http://json.schemastore.org/swagger-2.0#/definitions/security" }, "securityDefinitions": { - "$ref": "#/definitions/securityDefinitions" + "$ref": "http://json.schemastore.org/swagger-2.0#/definitions/securityDefinitions" }, "tags": { "type": "array", @@ -293,7 +293,7 @@ "default": false }, "security": { - "$ref": "#/definitions/security" + "$ref": "http://json.schemastore.org/swagger-2.0#/definitions/security" }, "x-ms-odata": { "$ref": "#/definitions/xmsOData" @@ -1265,23 +1265,6 @@ } } }, - "security": { - "type": "array", - "items": { - "$ref": "#/definitions/securityRequirement" - }, - "uniqueItems": true - }, - "securityRequirement": { - "type": "object", - "additionalProperties": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - } - }, "xml": { "type": "object", "additionalProperties": false, @@ -1333,252 +1316,6 @@ } } }, - "securityDefinitions": { - "type": "object", - "additionalProperties": { - "oneOf": [ - { - "$ref": "#/definitions/basicAuthenticationSecurity" - }, - { - "$ref": "#/definitions/apiKeySecurity" - }, - { - "$ref": "#/definitions/oauth2ImplicitSecurity" - }, - { - "$ref": "#/definitions/oauth2PasswordSecurity" - }, - { - "$ref": "#/definitions/oauth2ApplicationSecurity" - }, - { - "$ref": "#/definitions/oauth2AccessCodeSecurity" - } - ] - } - }, - "basicAuthenticationSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "basic" - ] - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "apiKeySecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "name", - "in" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "apiKey" - ] - }, - "name": { - "type": "string" - }, - "in": { - "type": "string", - "enum": [ - "header", - "query" - ] - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2ImplicitSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "authorizationUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "implicit" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "authorizationUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2PasswordSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "tokenUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "password" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "tokenUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2ApplicationSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "tokenUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "application" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "tokenUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2AccessCodeSecurity": { - "type": "object", - "additionalProperties": false, - "required": [ - "type", - "flow", - "authorizationUrl", - "tokenUrl" - ], - "properties": { - "type": { - "type": "string", - "enum": [ - "oauth2" - ] - }, - "flow": { - "type": "string", - "enum": [ - "accessCode" - ] - }, - "scopes": { - "$ref": "#/definitions/oauth2Scopes" - }, - "authorizationUrl": { - "type": "string", - "format": "uri" - }, - "tokenUrl": { - "type": "string", - "format": "uri" - }, - "description": { - "type": "string" - } - }, - "patternProperties": { - "^x-(?!ms-).*$": { - "$ref": "#/definitions/vendorExtension" - } - } - }, - "oauth2Scopes": { - "type": "object", - "additionalProperties": { - "type": "string" - } - }, "mediaTypeList": { "type": "array", "items": { @@ -1803,6 +1540,15 @@ "hostTemplate": { "type": "string" }, + "useSchemePrefix": { + "type": "boolean", + "default": true + }, + "positionInOperation": { + "type": "string", + "default": "first", + "pattern": "^(fir|la)st$" + }, "parameters": { "$ref": "#/definitions/xmsHostParametersList" }