From 63b9fd6403b55679f7a35931b880812f51456f1b Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Thu, 7 Apr 2016 21:17:27 -0700 Subject: [PATCH 01/13] Enhancement to x-ms-parameterized-host extension --- ...Generator.AzureResourceSchema.Tests.csproj | 4 +- .../AzureResourceSchema.Tests/packages.config | 14 +- .../CSharp/CSharp.Tests/AcceptanceTests.cs | 16 ++ ...toRestParameterizedCustomHostTestClient.cs | 128 +++++++++ ...toRestParameterizedCustomHostTestClient.cs | 57 ++++ .../CustomBaseUriMoreOptions/IPaths.cs | 47 ++++ .../CustomBaseUriMoreOptions/Models/Error.cs | 45 ++++ .../Models/ErrorException.cs | 99 +++++++ .../CustomBaseUriMoreOptions/Paths.cs | 203 +++++++++++++++ .../PathsExtensions.cs | 74 ++++++ .../Extensions/Extensions/Extensions.cs | 57 +++- .../Properties/Resources.Designer.cs | 9 + .../Extensions/Properties/Resources.resx | 3 + ...RestParameterizedCustomHostTestClient.java | 86 ++++++ ...ParameterizedCustomHostTestClientImpl.java | 121 +++++++++ .../PathsOperations.java | 75 ++++++ .../PathsOperationsImpl.java | 245 ++++++++++++++++++ .../models/Error.java | 64 +++++ .../models/ErrorException.java | 89 +++++++ .../models/package-info.java | 13 + .../package-info.java | 13 + .../AcceptanceTests/acceptanceTests.ts | 15 +- ...RestParameterizedCustomHostTestClient.d.ts | 44 ++++ ...toRestParameterizedCustomHostTestClient.js | 65 +++++ .../models/errorModel.js | 58 +++++ .../models/index.d.ts | 24 ++ .../CustomBaseUriMoreOptions/models/index.js | 17 ++ .../operations/index.d.ts | 44 ++++ .../operations/index.js | 17 ++ .../operations/paths.js | 167 ++++++++++++ .../__init__.py | 21 ++ ...t_parameterized_custom_host_test_client.py | 69 +++++ .../credentials.py | 15 ++ .../exceptions.py | 21 ++ .../models/__init__.py | 16 ++ .../models/error.py | 44 ++++ .../operations/__init__.py | 16 ++ .../operations/paths.py | 87 +++++++ .../version.py | 13 + .../CustomBaseUriMoreOptions/setup.py | 40 +++ .../Python/Python.Tests/Python.Tests.pyproj | 4 + AutoRest/TestServer/server/app.js | 2 + .../TestServer/server/routes/customUri.js | 11 + .../swagger/custom-baseUrl-more-options.json | 109 ++++++++ Documentation/swagger-extensions.md | 2 + gulpfile.js | 3 +- schema/swagger-extensions.json | 9 + 47 files changed, 2378 insertions(+), 17 deletions(-) create mode 100644 AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/AutoRestParameterizedCustomHostTestClient.cs create mode 100644 AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IAutoRestParameterizedCustomHostTestClient.cs create mode 100644 AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/IPaths.cs create mode 100644 AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/Error.cs create mode 100644 AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Models/ErrorException.cs create mode 100644 AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/Paths.cs create mode 100644 AutoRest/Generators/CSharp/CSharp.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/PathsExtensions.cs create mode 100644 AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClient.java create mode 100644 AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/AutoRestParameterizedCustomHostTestClientImpl.java create mode 100644 AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperations.java create mode 100644 AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/PathsOperationsImpl.java create mode 100644 AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/Error.java create mode 100644 AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/ErrorException.java create mode 100644 AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/models/package-info.java create mode 100644 AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/custombaseurimoreoptions/package-info.java create mode 100644 AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.d.ts create mode 100644 AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autoRestParameterizedCustomHostTestClient.js create mode 100644 AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/errorModel.js create mode 100644 AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.d.ts create mode 100644 AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/models/index.js create mode 100644 AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.d.ts create mode 100644 AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/index.js create mode 100644 AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/operations/paths.js create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/__init__.py create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/auto_rest_parameterized_custom_host_test_client.py create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/credentials.py create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/exceptions.py create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/__init__.py create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/models/error.py create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/__init__.py create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/operations/paths.py create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/version.py create mode 100644 AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/setup.py create mode 100644 AutoRest/TestServer/swagger/custom-baseUrl-more-options.json diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj index 079278b9d7..01522ea89f 100644 --- a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/AutoRest.Generator.AzureResourceSchema.Tests.csproj @@ -62,7 +62,9 @@ - + + PreserveNewest + diff --git a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config index 64fb5d7b3b..4e690e09d9 100644 --- a/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config +++ b/AutoRest/Generators/AzureResourceSchema/AzureResourceSchema.Tests/packages.config @@ -1,10 +1,10 @@  - - - - - - - + + + + + + + \ No newline at end of file diff --git a/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs b/AutoRest/Generators/CSharp/CSharp.Tests/AcceptanceTests.cs index 0c6e31b1c1..0d5c31f0e5 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; @@ -1951,6 +1952,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() { 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 0000000000..e680cbe6a8 --- /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 0000000000..87db999d81 --- /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 0000000000..a117b914e7 --- /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 0000000000..82a4873e61 --- /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 0000000000..e3ab1c0a08 --- /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 0000000000..a8599cf083 --- /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 0000000000..c553414304 --- /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/Extensions/Extensions/Extensions.cs b/AutoRest/Generators/Extensions/Extensions/Extensions.cs index e974d9563a..b80820b8c0 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 = "last"; + + 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); + } + } } } diff --git a/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs b/AutoRest/Generators/Extensions/Extensions/Properties/Resources.Designer.cs index 689a601b82..f98e2ea0b0 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 d06a580a71..7df584f0a4 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/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 0000000000..7c5bb29be0 --- /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 0000000000..ad9fe946dc --- /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 0000000000..6273f3426d --- /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 0000000000..1399472025 --- /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 0000000000..73232cf4ed --- /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 0000000000..0c4458e200 --- /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 0000000000..b5c9a91ec9 --- /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 0000000000..a6434083eb --- /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/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts index c7404da84e..0a81b34200 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); @@ -94,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) { 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 0000000000..98c22ab85f --- /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 0000000000..391f7b50de --- /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 0000000000..663be0f4aa --- /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 0000000000..5405a199a0 --- /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 0000000000..3430295d8b --- /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 0000000000..3fa4ea5d9b --- /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 0000000000..412d88e676 --- /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 0000000000..dc2c66f05c --- /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/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 0000000000..6711cf5b14 --- /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 0000000000..1e9140c3e5 --- /dev/null +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/CustomBaseUriMoreOptions/autorestparameterizedcustomhosttestclient/auto_rest_parameterized_custom_host_test_client.py @@ -0,0 +1,69 @@ +# 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('subscription_id must not be None.') + if dns_suffix is None: + raise ValueError('dns_suffix must not be None.') + 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 0000000000..0d097b4f2a --- /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 0000000000..c3cc002260 --- /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 0000000000..fd6d517a47 --- /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 0000000000..c2d19e377e --- /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 0000000000..fa4a82a28d --- /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 0000000000..2c43f455f7 --- /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 0000000000..a39916c162 --- /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 0000000000..3521fb6abe --- /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/Python.Tests.pyproj b/AutoRest/Generators/Python/Python.Tests/Python.Tests.pyproj index 551692fe3e..b6cfb6ea96 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/TestServer/server/app.js b/AutoRest/TestServer/server/app.js index f0da0d6068..8bb3b105ba 100644 --- a/AutoRest/TestServer/server/app.js +++ b/AutoRest/TestServer/server/app.js @@ -428,6 +428,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, diff --git a/AutoRest/TestServer/server/routes/customUri.js b/AutoRest/TestServer/server/routes/customUri.js index 2eee79cadf..85d074cdec 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/swagger/custom-baseUrl-more-options.json b/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json new file mode 100644 index 0000000000..875759e680 --- /dev/null +++ b/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json @@ -0,0 +1,109 @@ +{ + "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, + "positionInOperation": "first", + "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/Documentation/swagger-extensions.md b/Documentation/swagger-extensions.md index cb3bed17ab..dba70ead92 100644 --- a/Documentation/swagger-extensions.md +++ b/Documentation/swagger-extensions.md @@ -389,6 +389,8 @@ When used, replaces the standard Swagger "host" attribute with a host that conta Field Name | Type | Description ---|:---:|--- hostTemplate | `string` | **Required**. Specifies the parameterized template for the host. +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: last**. 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"**. 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" **Example**: diff --git a/gulpfile.js b/gulpfile.js index 942ac3a898..e7bc6be0ad 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 = { diff --git a/schema/swagger-extensions.json b/schema/swagger-extensions.json index 199078f32e..8b93156a83 100644 --- a/schema/swagger-extensions.json +++ b/schema/swagger-extensions.json @@ -1540,6 +1540,15 @@ "hostTemplate": { "type": "string" }, + "useSchemePrefix": { + "type": "boolean", + "default": true + }, + "positionInOperation": { + "type": "string", + "default": "end", + "pattern": "^(fir|la)st$" + }, "parameters": { "$ref": "#/definitions/xmsHostParametersList" } From d8110cffea020031b48f5c85c2e61493144c5328 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Sat, 9 Apr 2016 12:14:03 -0700 Subject: [PATCH 02/13] positionInOperation defaults to first --- AutoRest/Generators/Extensions/Extensions/Extensions.cs | 2 +- AutoRest/TestServer/swagger/custom-baseUrl-more-options.json | 1 - AutoRest/TestServer/swagger/custom-baseUrl.json | 1 + Documentation/swagger-extensions.md | 4 ++-- schema/swagger-extensions.json | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/AutoRest/Generators/Extensions/Extensions/Extensions.cs b/AutoRest/Generators/Extensions/Extensions/Extensions.cs index b80820b8c0..620a2d594c 100644 --- a/AutoRest/Generators/Extensions/Extensions/Extensions.cs +++ b/AutoRest/Generators/Extensions/Extensions/Extensions.cs @@ -77,7 +77,7 @@ public static void ProcessParameterizedHost(ServiceClient serviceClient, Setting useSchemePrefix = bool.Parse(hostExtension[UseSchemePrefix].ToString()); } - var position = "last"; + var position = "first"; if (hostExtension[PositionInOperation] != null) { diff --git a/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json b/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json index 875759e680..75ef745397 100644 --- a/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json +++ b/AutoRest/TestServer/swagger/custom-baseUrl-more-options.json @@ -8,7 +8,6 @@ "x-ms-parameterized-host": { "hostTemplate": "{vault}{secret}{dnsSuffix}", "useSchemePrefix": false, - "positionInOperation": "first", "parameters": [ { "name": "vault", diff --git a/AutoRest/TestServer/swagger/custom-baseUrl.json b/AutoRest/TestServer/swagger/custom-baseUrl.json index 5ca07d1627..aaa0309f4b 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/Documentation/swagger-extensions.md b/Documentation/swagger-extensions.md index dba70ead92..f606ac3355 100644 --- a/Documentation/swagger-extensions.md +++ b/Documentation/swagger-extensions.md @@ -390,8 +390,8 @@ Field Name | Type | Description ---|:---:|--- hostTemplate | `string` | **Required**. Specifies the parameterized template for the host. 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: last**. 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"**. -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" +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 diff --git a/schema/swagger-extensions.json b/schema/swagger-extensions.json index 8b93156a83..6e6476c56d 100644 --- a/schema/swagger-extensions.json +++ b/schema/swagger-extensions.json @@ -1546,7 +1546,7 @@ }, "positionInOperation": { "type": "string", - "default": "end", + "default": "first", "pattern": "^(fir|la)st$" }, "parameters": { From 77502840467ecb898f2a665ed040be9f7885a40b Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Thu, 28 Apr 2016 12:35:26 -0700 Subject: [PATCH 03/13] fixed setting default value for a complex object containing constant properties. --- .../AcceptanceTests/Lro/operations/index.d.ts | 46 ++ .../AcceptanceTests/Lro/operations/lROSADs.js | 249 ++++++++++ .../BodyInteger/operations/index.d.ts | 58 +++ .../BodyInteger/operations/intModel.js | 463 ++++++++++++++++++ .../operations/index.d.ts | 58 +++ .../operations/intModel.js | 463 ++++++++++++++++++ .../ModelFlattening/models/simpleProduct.js | 1 - .../AcceptanceTests/Url/operations/index.d.ts | 16 + .../AcceptanceTests/Url/operations/paths.js | 102 ++++ .../Validation/models/childProduct.js | 1 - .../Validation/models/constantProduct.js | 1 - .../Validation/models/product.js | 1 - .../NodeJS/NodeJS/ClientModelExtensions.cs | 16 +- 13 files changed, 1464 insertions(+), 11 deletions(-) diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/Lro/operations/index.d.ts b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/Lro/operations/index.d.ts index ec051455be..01c4539431 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/Lro/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/Lro/operations/index.d.ts @@ -1908,6 +1908,52 @@ export interface LROSADs { beginPutNonRetry201Creating400(options: { product? : models.Product, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; beginPutNonRetry201Creating400(callback: ServiceCallback): void; + /** + * Long running put request, service returns a Product with + * 'ProvisioningState' = 'Creating' and 201 response code + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.product] Product to put + * + * @param {string} [options.product.provisioningState] + * + * @param {object} [options.product.tags] + * + * @param {string} [options.product.location] Resource Location + * + * @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 + */ + putNonRetry201Creating400InvalidJson(options: { product? : models.Product, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + putNonRetry201Creating400InvalidJson(callback: ServiceCallback): void; + + /** + * Long running put request, service returns a Product with + * 'ProvisioningState' = 'Creating' and 201 response code + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.product] Product to put + * + * @param {string} [options.product.provisioningState] + * + * @param {object} [options.product.tags] + * + * @param {string} [options.product.location] Resource Location + * + * @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 + */ + beginPutNonRetry201Creating400InvalidJson(options: { product? : models.Product, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + beginPutNonRetry201Creating400InvalidJson(callback: ServiceCallback): void; + /** * Long running put request, service returns a 200 with * ProvisioningState=’Creating’. Poll the endpoint indicated in the diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/Lro/operations/lROSADs.js b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/Lro/operations/lROSADs.js index 33fff60783..b82dd78f09 100644 --- a/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/Lro/operations/lROSADs.js +++ b/AutoRest/Generators/NodeJS/Azure.NodeJS.Tests/Expected/AcceptanceTests/Lro/operations/lROSADs.js @@ -525,6 +525,255 @@ LROSADs.prototype.beginPutNonRetry201Creating400 = function (options, callback) }); }; +/** + * + * Long running put request, service returns a Product with + * 'ProvisioningState' = 'Creating' and 201 response code + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.product] Product to put + * + * @param {string} [options.product.provisioningState] + * + * @param {object} [options.product.tags] + * + * @param {string} [options.product.location] Resource Location + * + * @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. + * See {@link Product} for more information. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +LROSADs.prototype.putNonRetry201Creating400InvalidJson = 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.'); + } + + // Send request + this.beginPutNonRetry201Creating400InvalidJson(options, function (err, parsedResult, httpRequest, response){ + if (err) return callback(err); + + var initialResult = new msRest.HttpOperationResponse(); + initialResult.request = httpRequest; + initialResult.response = response; + initialResult.body = response.body; + client.getPutOrPatchOperationResult(initialResult, options, function (err, pollingResult) { + if (err) return callback(err); + + // Create Result + var result = null; + httpRequest = pollingResult.request; + response = pollingResult.response; + var responseBody = pollingResult.body; + if (responseBody === '') responseBody = null; + + // Deserialize Response + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = new client.models['Product']().mapper(); + 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); + }); + }); +}; + +/** + * Long running put request, service returns a Product with + * 'ProvisioningState' = 'Creating' and 201 response code + * + * @param {object} [options] Optional Parameters. + * + * @param {object} [options.product] Product to put + * + * @param {string} [options.product.provisioningState] + * + * @param {object} [options.product.tags] + * + * @param {string} [options.product.location] Resource Location + * + * @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. + * See {@link Product} for more information. + * + * {object} [request] - The HTTP Request object if an error did not occur. + * + * {stream} [response] - The HTTP Response stream if an error did not occur. + */ +LROSADs.prototype.beginPutNonRetry201Creating400InvalidJson = 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.'); + } + var product = (options && options.product !== undefined) ? options.product : undefined; + // Validate + try { + if (this.client.acceptLanguage !== null && this.client.acceptLanguage !== undefined && typeof this.client.acceptLanguage.valueOf() !== 'string') { + throw new Error('this.client.acceptLanguage must be of type string.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//lro/nonretryerror/put/201/creating/400/invalidjson'; + var queryParameters = []; + 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 = 'PUT'; + httpRequest.headers = {}; + httpRequest.url = requestUrl; + // Set Headers + if (this.client.generateClientRequestId) { + httpRequest.headers['x-ms-client-request-id'] = msRestAzure.generateUuid(); + } + if (this.client.acceptLanguage !== undefined && this.client.acceptLanguage !== null) { + httpRequest.headers['accept-language'] = this.client.acceptLanguage; + } + 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 (product !== null && product !== undefined) { + var requestModelMapper = new client.models['Product']().mapper(); + requestModel = client.serialize(requestModelMapper, product, 'product'); + requestContent = JSON.stringify(requestModel); + } + } catch (error) { + var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + + 'payload - "%s"', error.message, util.inspect(product, {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 && statusCode !== 201) { + 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['CloudError']().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 = new client.models['Product']().mapper(); + 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); + } + } + // Deserialize Response + if (statusCode === 201) { + var parsedResponse = null; + try { + parsedResponse = JSON.parse(responseBody); + result = JSON.parse(responseBody); + if (parsedResponse !== null && parsedResponse !== undefined) { + var resultMapper = new client.models['Product']().mapper(); + result = client.deserialize(resultMapper, parsedResponse, 'result'); + } + } catch (error) { + var deserializationError1 = new Error(util.format('Error "%s" occurred in deserializing the responseBody - "%s"', error, responseBody)); + deserializationError1.request = msRest.stripRequest(httpRequest); + deserializationError1.response = msRest.stripResponse(response); + return callback(deserializationError1); + } + } + + return callback(null, result, httpRequest, response); + }); +}; + /** * * Long running put request, service returns a 200 with diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/index.d.ts index 26ce14eb33..1b00b43d81 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/index.d.ts @@ -167,4 +167,62 @@ export interface IntModel { */ putMin64(intBody: number, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; putMin64(intBody: number, callback: ServiceCallback): void; + + /** + * Get datetime encoded as Unix time 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 + */ + getUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getUnixTime(callback: ServiceCallback): void; + + /** + * Put datetime encoded as Unix time + * + * @param {number} intBody + * + * @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 + */ + putUnixTimeDate(intBody: number, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + putUnixTimeDate(intBody: number, callback: ServiceCallback): void; + + /** + * Get invalid Unix time 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 + */ + getInvalidUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getInvalidUnixTime(callback: ServiceCallback): void; + + /** + * Get null Unix time 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 + */ + getNullUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getNullUnixTime(callback: ServiceCallback): void; } diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/intModel.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/intModel.js index 81595128f8..b1ed3fbf47 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/intModel.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/intModel.js @@ -1196,5 +1196,468 @@ IntModel.prototype.putMin64 = function (intBody, options, callback) { }); }; +/** + * Get datetime encoded as Unix time 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. + * + * {number} [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. + */ +IntModel.prototype.getUnixTime = 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 + + '//int/unixtime'; + // 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: 'Number' + } + }; + 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 datetime encoded as Unix time + * + * @param {number} intBody + * + * @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. + */ +IntModel.prototype.putUnixTimeDate = function (intBody, 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 (intBody === null || intBody === undefined || typeof intBody !== 'number') { + throw new Error('intBody cannot be null or undefined and it must be of type number.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//int/unixtime'; + // 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 (intBody !== null && intBody !== undefined) { + var requestModelMapper = { + required: true, + serializedName: 'intBody', + type: { + name: 'Number' + } + }; + requestModel = client.serialize(requestModelMapper, intBody, 'intBody'); + requestContent = JSON.stringify(requestModel); + } + } catch (error) { + var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + + 'payload - "%s"', error.message, util.inspect(intBody, {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 invalid Unix time 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. + * + * {number} [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. + */ +IntModel.prototype.getInvalidUnixTime = 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 + + '//int/invalidunixtime'; + // 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: 'Number' + } + }; + 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 null Unix time 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. + * + * {number} [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. + */ +IntModel.prototype.getNullUnixTime = 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 + + '//int/nullunixtime'; + // 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: 'Number' + } + }; + 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 = IntModel; diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/index.d.ts index 8238ac41b5..ac60442293 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/index.d.ts @@ -264,4 +264,62 @@ export interface IntModel { */ putMin64(intBody: number, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; putMin64(intBody: number, callback: ServiceCallback): void; + + /** + * Get datetime encoded as Unix time 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 + */ + getUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getUnixTime(callback: ServiceCallback): void; + + /** + * Put datetime encoded as Unix time + * + * @param {number} intBody + * + * @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 + */ + putUnixTimeDate(intBody: number, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + putUnixTimeDate(intBody: number, callback: ServiceCallback): void; + + /** + * Get invalid Unix time 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 + */ + getInvalidUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getInvalidUnixTime(callback: ServiceCallback): void; + + /** + * Get null Unix time 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 + */ + getNullUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getNullUnixTime(callback: ServiceCallback): void; } diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/intModel.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/intModel.js index e7c05cfad0..42f1d72ab3 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/intModel.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/intModel.js @@ -1196,5 +1196,468 @@ IntModel.prototype.putMin64 = function (intBody, options, callback) { }); }; +/** + * Get datetime encoded as Unix time 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. + * + * {number} [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. + */ +IntModel.prototype.getUnixTime = 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 + + '//int/unixtime'; + // 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: 'Number' + } + }; + 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 datetime encoded as Unix time + * + * @param {number} intBody + * + * @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. + */ +IntModel.prototype.putUnixTimeDate = function (intBody, 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 (intBody === null || intBody === undefined || typeof intBody !== 'number') { + throw new Error('intBody cannot be null or undefined and it must be of type number.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//int/unixtime'; + // 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 (intBody !== null && intBody !== undefined) { + var requestModelMapper = { + required: true, + serializedName: 'intBody', + type: { + name: 'Number' + } + }; + requestModel = client.serialize(requestModelMapper, intBody, 'intBody'); + requestContent = JSON.stringify(requestModel); + } + } catch (error) { + var serializationError = new Error(util.format('Error "%s" occurred in serializing the ' + + 'payload - "%s"', error.message, util.inspect(intBody, {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 invalid Unix time 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. + * + * {number} [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. + */ +IntModel.prototype.getInvalidUnixTime = 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 + + '//int/invalidunixtime'; + // 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: 'Number' + } + }; + 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 null Unix time 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. + * + * {number} [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. + */ +IntModel.prototype.getNullUnixTime = 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 + + '//int/nullunixtime'; + // 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: 'Number' + } + }; + 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 = IntModel; 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 3e66a747ff..cca28edbd8 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 @@ -42,7 +42,6 @@ SimpleProduct.prototype.mapper = function () { return { required: false, serializedName: 'SimpleProduct', - defaultValue: {}, type: { name: 'Composite', className: 'SimpleProduct', 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 3d9f5f55e7..3f5e246438 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 @@ -394,6 +394,22 @@ export interface Paths { */ arrayCsvInPath(arrayPath: string[], options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; arrayCsvInPath(arrayPath: string[], callback: ServiceCallback): void; + + /** + * Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + * + * @param {number} unixTimeUrlPath Unix time 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 + */ + unixTimeUrl(unixTimeUrlPath: number, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + unixTimeUrl(unixTimeUrlPath: number, 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 ac14e44e19..4039b0ce96 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 @@ -2458,5 +2458,107 @@ Paths.prototype.arrayCsvInPath = function (arrayPath, options, callback) { }); }; +/** + * Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + * + * @param {number} unixTimeUrlPath Unix time 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.unixTimeUrl = function (unixTimeUrlPath, 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 (unixTimeUrlPath === null || unixTimeUrlPath === undefined || typeof unixTimeUrlPath !== 'number') { + throw new Error('unixTimeUrlPath cannot be null or undefined and it must be of type number.'); + } + } catch (error) { + return callback(error); + } + + // Construct URL + var requestUrl = this.client.baseUri + + '//paths/int/1460505600/{unixTimeUrlPath}'; + requestUrl = requestUrl.replace('{unixTimeUrlPath}', encodeURIComponent(unixTimeUrlPath.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.Tests/Expected/AcceptanceTests/Validation/models/childProduct.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/childProduct.js index 212a2c646e..14cb8cf926 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/childProduct.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/childProduct.js @@ -31,7 +31,6 @@ ChildProduct.prototype.mapper = function () { return { required: false, serializedName: 'ChildProduct', - defaultValue: {}, type: { name: 'Composite', className: 'ChildProduct', diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/constantProduct.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/constantProduct.js index e79e409278..cd97a2c928 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/constantProduct.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/constantProduct.js @@ -29,7 +29,6 @@ ConstantProduct.prototype.mapper = function () { return { required: false, serializedName: 'ConstantProduct', - defaultValue: {}, type: { name: 'Composite', className: 'ConstantProduct', diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/product.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/product.js index 6af3595ad5..ee09ede6f6 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/product.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/Validation/models/product.js @@ -47,7 +47,6 @@ Product.prototype.mapper = function () { return { required: false, serializedName: 'Product', - defaultValue: {}, type: { name: 'Composite', className: 'Product', diff --git a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs index c842b28b32..8f36adeec8 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs @@ -195,7 +195,8 @@ private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvid primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || - primary.Type == KnownPrimaryType.Object) + primary.Type == KnownPrimaryType.Object || + primary.Type == KnownPrimaryType.UnixTime) { if (isRequired) { @@ -302,7 +303,7 @@ private static string PrimaryTSType(this PrimaryType primary) if (primary.Type == KnownPrimaryType.Boolean) return "boolean"; - else if (primary.Type == KnownPrimaryType.Double || primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long) + else if (primary.Type == KnownPrimaryType.Double || primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || primary.Type == KnownPrimaryType.UnixTime) return "number"; else if (primary.Type == KnownPrimaryType.String || primary.Type == KnownPrimaryType.Uuid) return "string"; @@ -666,9 +667,9 @@ public static IndentedStringBuilder AppendConstraintValidations(this IType type, public static string ConstructMapper(this IType type, string serializedName, IParameter parameter, bool isPageable, bool expandComposite) { var builder = new IndentedStringBuilder(" "); - string defaultValue = null; - bool isRequired = false; - bool isConstant = false; + string defaultValue = null; + bool isRequired = false; + bool isConstant = false; bool isReadOnly = false; Dictionary constraints = null; var property = parameter as Property; @@ -684,7 +685,7 @@ public static string ConstructMapper(this IType type, string serializedName, IPa isReadOnly = property.IsReadOnly; } CompositeType composite = type as CompositeType; - if (composite != null && composite.ContainsConstantProperties) + if (composite != null && composite.ContainsConstantProperties && (parameter != null && parameter.IsRequired)) { defaultValue = "{}"; } @@ -746,7 +747,8 @@ public static string ConstructMapper(this IType type, string serializedName, IPa { builder.AppendLine("type: {").Indent().AppendLine("name: 'Boolean'").Outdent().AppendLine("}"); } - else if(primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Double) + else if(primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || primary.Type == KnownPrimaryType.Decimal || + primary.Type == KnownPrimaryType.Double || primary.Type == KnownPrimaryType.UnixTime) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Number'").Outdent().AppendLine("}"); } From 845fc5b0356d30706926fae6624365c2efa955f9 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Thu, 28 Apr 2016 12:36:58 -0700 Subject: [PATCH 04/13] result of executing gulp regenerate:expected --- .../java/fixtures/lro/LROSADsOperations.java | 76 +++++++ .../fixtures/lro/LROSADsOperationsImpl.java | 181 +++++++++++++++ .../fixtures/bodyinteger/IntOperations.java | 75 +++++++ .../bodyinteger/IntOperationsImpl.java | 206 ++++++++++++++++++ .../java/fixtures/url/PathsOperations.java | 21 ++ .../fixtures/url/PathsOperationsImpl.java | 59 +++++ .../operations/lrosa_ds_operations.py | 86 ++++++++ .../operations/int_model.py | 175 +++++++++++++++ .../operations/paths.py | 43 ++++ 9 files changed, 922 insertions(+) diff --git a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperations.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperations.java index 67695190d0..7fdc2cc170 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperations.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperations.java @@ -195,6 +195,82 @@ public interface LROSADsOperations { */ ServiceCall beginPutNonRetry201Creating400Async(Product product, final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @throws CloudException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws InterruptedException exception thrown when long running operation is interrupted + * @return the Product object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse putNonRetry201Creating400InvalidJson() throws CloudException, IOException, InterruptedException; + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall putNonRetry201Creating400InvalidJsonAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param product Product to put + * @throws CloudException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws InterruptedException exception thrown when long running operation is interrupted + * @return the Product object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse putNonRetry201Creating400InvalidJson(Product product) throws CloudException, IOException, InterruptedException; + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param product Product to put + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall putNonRetry201Creating400InvalidJsonAsync(Product product, final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @throws CloudException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the Product object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse beginPutNonRetry201Creating400InvalidJson() throws CloudException, IOException; + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall beginPutNonRetry201Creating400InvalidJsonAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param product Product to put + * @throws CloudException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the Product object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse beginPutNonRetry201Creating400InvalidJson(Product product) throws CloudException, IOException; + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param product Product to put + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + ServiceCall beginPutNonRetry201Creating400InvalidJsonAsync(Product product, final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** * 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/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperationsImpl.java b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperationsImpl.java index a00b4293ab..2f3623d834 100644 --- a/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperationsImpl.java +++ b/AutoRest/Generators/Java/Azure.Java.Tests/src/main/java/fixtures/lro/LROSADsOperationsImpl.java @@ -95,6 +95,14 @@ interface LROSADsService { @PUT("lro/nonretryerror/put/201/creating/400") Call beginPutNonRetry201Creating400(@Body Product product, @Header("accept-language") String acceptLanguage); + @Headers("Content-Type: application/json; charset=utf-8") + @PUT("lro/nonretryerror/put/201/creating/400/invalidjson") + Call putNonRetry201Creating400InvalidJson(@Body Product product, @Header("accept-language") String acceptLanguage); + + @Headers("Content-Type: application/json; charset=utf-8") + @PUT("lro/nonretryerror/put/201/creating/400/invalidjson") + Call beginPutNonRetry201Creating400InvalidJson(@Body Product product, @Header("accept-language") String acceptLanguage); + @Headers("Content-Type: application/json; charset=utf-8") @PUT("lro/nonretryerror/putasync/retry/400") Call putAsyncRelativeRetry400(@Body Product product, @Header("accept-language") String acceptLanguage); @@ -627,6 +635,179 @@ private ServiceResponse beginPutNonRetry201Creating400Delegate(Response .build(response); } + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @throws CloudException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws InterruptedException exception thrown when long running operation is interrupted + * @return the Product object wrapped in ServiceResponse if successful. + */ + public ServiceResponse putNonRetry201Creating400InvalidJson() throws CloudException, IOException, InterruptedException { + final Product product = null; + Response result = service.putNonRetry201Creating400InvalidJson(product, this.client.getAcceptLanguage()).execute(); + return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); + } + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + public ServiceCall putNonRetry201Creating400InvalidJsonAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + final Product product = null; + Call call = service.putNonRetry201Creating400InvalidJson(product, this.client.getAcceptLanguage()); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new Callback() { + @Override + public void onFailure(Call call, Throwable t) { + serviceCallback.failure(t); + } + @Override + public void onResponse(Call call, Response response) { + client.getAzureClient().getPutOrPatchResultAsync(response, new TypeToken() { }.getType(), serviceCall, serviceCallback); + } + }); + return serviceCall; + } + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param product Product to put + * @throws CloudException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @throws InterruptedException exception thrown when long running operation is interrupted + * @return the Product object wrapped in ServiceResponse if successful. + */ + public ServiceResponse putNonRetry201Creating400InvalidJson(Product product) throws CloudException, IOException, InterruptedException { + Validator.validate(product); + Response result = service.putNonRetry201Creating400InvalidJson(product, this.client.getAcceptLanguage()).execute(); + return client.getAzureClient().getPutOrPatchResult(result, new TypeToken() { }.getType()); + } + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param product Product to put + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if callback is null + * @return the {@link ServiceCall} object + */ + public ServiceCall putNonRetry201Creating400InvalidJsonAsync(Product product, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Validator.validate(product, serviceCallback); + Call call = service.putNonRetry201Creating400InvalidJson(product, this.client.getAcceptLanguage()); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new Callback() { + @Override + public void onFailure(Call call, Throwable t) { + serviceCallback.failure(t); + } + @Override + public void onResponse(Call call, Response response) { + client.getAzureClient().getPutOrPatchResultAsync(response, new TypeToken() { }.getType(), serviceCall, serviceCallback); + } + }); + return serviceCall; + } + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @throws CloudException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the Product object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse beginPutNonRetry201Creating400InvalidJson() throws CloudException, IOException { + final Product product = null; + Call call = service.beginPutNonRetry201Creating400InvalidJson(product, this.client.getAcceptLanguage()); + return beginPutNonRetry201Creating400InvalidJsonDelegate(call.execute()); + } + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @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 beginPutNonRetry201Creating400InvalidJsonAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + final Product product = null; + Call call = service.beginPutNonRetry201Creating400InvalidJson(product, this.client.getAcceptLanguage()); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(beginPutNonRetry201Creating400InvalidJsonDelegate(response)); + } catch (CloudException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param product Product to put + * @throws CloudException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the Product object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse beginPutNonRetry201Creating400InvalidJson(Product product) throws CloudException, IOException { + Validator.validate(product); + Call call = service.beginPutNonRetry201Creating400InvalidJson(product, this.client.getAcceptLanguage()); + return beginPutNonRetry201Creating400InvalidJsonDelegate(call.execute()); + } + + /** + * Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and 201 response code. + * + * @param product Product to put + * @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 beginPutNonRetry201Creating400InvalidJsonAsync(Product product, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Validator.validate(product, serviceCallback); + Call call = service.beginPutNonRetry201Creating400InvalidJson(product, this.client.getAcceptLanguage()); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(beginPutNonRetry201Creating400InvalidJsonDelegate(response)); + } catch (CloudException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse beginPutNonRetry201Creating400InvalidJsonDelegate(Response response) throws CloudException, IOException { + return new AzureServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + /** * 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/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/bodyinteger/IntOperations.java index 2f705c55d8..06d2cb2eb7 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 @@ -209,4 +209,79 @@ public interface IntOperations { */ ServiceCall putMin64Async(long intBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Get datetime encoded as Unix time value. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the long object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse getUnixTime() throws ErrorException, IOException; + + /** + * Get datetime encoded as Unix time 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 getUnixTimeAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Put datetime encoded as Unix time. + * + * @param intBody the long 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 putUnixTimeDate(long intBody) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Put datetime encoded as Unix time. + * + * @param intBody the long 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 putUnixTimeDateAsync(long intBody, final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Get invalid Unix time value. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the long object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse getInvalidUnixTime() throws ErrorException, IOException; + + /** + * Get invalid Unix time 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 getInvalidUnixTimeAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + + /** + * Get null Unix time value. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the long object wrapped in {@link ServiceResponse} if successful. + */ + ServiceResponse getNullUnixTime() throws ErrorException, IOException; + + /** + * Get null Unix time 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 getNullUnixTimeAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException; + } 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 8e9325c0ca..58cd455e4d 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 @@ -93,6 +93,22 @@ interface IntService { @PUT("int/min/64") Call putMin64(@Body long intBody); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("int/unixtime") + Call getUnixTime(); + + @Headers("Content-Type: application/json; charset=utf-8") + @PUT("int/unixtime") + Call putUnixTimeDate(@Body long intBody); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("int/invalidunixtime") + Call getInvalidUnixTime(); + + @Headers("Content-Type: application/json; charset=utf-8") + @GET("int/nullunixtime") + Call getNullUnixTime(); + } /** @@ -553,4 +569,194 @@ private ServiceResponse putMin64Delegate(Response response) .build(response); } + /** + * Get datetime encoded as Unix time value. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the long object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse getUnixTime() throws ErrorException, IOException { + Call call = service.getUnixTime(); + return getUnixTimeDelegate(call.execute()); + } + + /** + * Get datetime encoded as Unix time 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 getUnixTimeAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getUnixTime(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getUnixTimeDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getUnixTimeDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Put datetime encoded as Unix time. + * + * @param intBody the long 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 putUnixTimeDate(long intBody) throws ErrorException, IOException, IllegalArgumentException { + if (intBody == null) { + throw new IllegalArgumentException("Parameter intBody is required and cannot be null."); + } + Call call = service.putUnixTimeDate(intBody); + return putUnixTimeDateDelegate(call.execute()); + } + + /** + * Put datetime encoded as Unix time. + * + * @param intBody the long 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 putUnixTimeDateAsync(long intBody, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (intBody == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter intBody is required and cannot be null.")); + return null; + } + Call call = service.putUnixTimeDate(intBody); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(putUnixTimeDateDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse putUnixTimeDateDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Get invalid Unix time value. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the long object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse getInvalidUnixTime() throws ErrorException, IOException { + Call call = service.getInvalidUnixTime(); + return getInvalidUnixTimeDelegate(call.execute()); + } + + /** + * Get invalid Unix time 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 getInvalidUnixTimeAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getInvalidUnixTime(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getInvalidUnixTimeDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getInvalidUnixTimeDelegate(Response response) throws ErrorException, IOException { + return new ServiceResponseBuilder(this.client.getMapperAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorException.class) + .build(response); + } + + /** + * Get null Unix time value. + * + * @throws ErrorException exception thrown from REST call + * @throws IOException exception thrown from serialization/deserialization + * @return the long object wrapped in {@link ServiceResponse} if successful. + */ + public ServiceResponse getNullUnixTime() throws ErrorException, IOException { + Call call = service.getNullUnixTime(); + return getNullUnixTimeDelegate(call.execute()); + } + + /** + * Get null Unix time 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 getNullUnixTimeAsync(final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + Call call = service.getNullUnixTime(); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(getNullUnixTimeDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse getNullUnixTimeDelegate(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/url/PathsOperations.java b/AutoRest/Generators/Java/Java.Tests/src/main/java/fixtures/url/PathsOperations.java index f7676a65a5..6f82029407 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 @@ -502,4 +502,25 @@ public interface PathsOperations { */ ServiceCall arrayCsvInPathAsync(List arrayPath, final ServiceCallback serviceCallback) throws IllegalArgumentException; + /** + * Get the date 2016-04-13 encoded value as '1460505600' (Unix time). + * + * @param unixTimeUrlPath Unix time 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 unixTimeUrl(long unixTimeUrlPath) throws ErrorException, IOException, IllegalArgumentException; + + /** + * Get the date 2016-04-13 encoded value as '1460505600' (Unix time). + * + * @param unixTimeUrlPath Unix time 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 unixTimeUrlAsync(long unixTimeUrlPath, 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 b32c2fcbd2..60f4ea1452 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 @@ -159,6 +159,10 @@ interface PathsService { @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); + @Headers("Content-Type: application/json; charset=utf-8") + @GET("paths/int/1460505600/{unixTimeUrlPath}") + Call unixTimeUrl(@Path("unixTimeUrlPath") long unixTimeUrlPath); + } /** @@ -1418,4 +1422,59 @@ private ServiceResponse arrayCsvInPathDelegate(Response resp .build(response); } + /** + * Get the date 2016-04-13 encoded value as '1460505600' (Unix time). + * + * @param unixTimeUrlPath Unix time 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 unixTimeUrl(long unixTimeUrlPath) throws ErrorException, IOException, IllegalArgumentException { + if (unixTimeUrlPath == null) { + throw new IllegalArgumentException("Parameter unixTimeUrlPath is required and cannot be null."); + } + Call call = service.unixTimeUrl(unixTimeUrlPath); + return unixTimeUrlDelegate(call.execute()); + } + + /** + * Get the date 2016-04-13 encoded value as '1460505600' (Unix time). + * + * @param unixTimeUrlPath Unix time 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 unixTimeUrlAsync(long unixTimeUrlPath, final ServiceCallback serviceCallback) throws IllegalArgumentException { + if (serviceCallback == null) { + throw new IllegalArgumentException("ServiceCallback is required for async calls."); + } + if (unixTimeUrlPath == null) { + serviceCallback.failure(new IllegalArgumentException("Parameter unixTimeUrlPath is required and cannot be null.")); + return null; + } + Call call = service.unixTimeUrl(unixTimeUrlPath); + final ServiceCall serviceCall = new ServiceCall(call); + call.enqueue(new ServiceResponseCallback(serviceCallback) { + @Override + public void onResponse(Call call, Response response) { + try { + serviceCallback.success(unixTimeUrlDelegate(response)); + } catch (ErrorException | IOException exception) { + serviceCallback.failure(exception); + } + } + }); + return serviceCall; + } + + private ServiceResponse unixTimeUrlDelegate(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/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 f4bb777ced..a211b6975e 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 @@ -205,6 +205,92 @@ def get_long_running_output(response): long_running_send, get_long_running_output, get_long_running_status, long_running_operation_timeout) + def put_non_retry201_creating400_invalid_json( + self, product=None, custom_headers={}, raw=False, **operation_config): + """ + Long running put request, service returns a Product with + 'ProvisioningState' = 'Creating' and 201 response code + + :param product: Product to put + :type product: :class:`Product + ` + :param dict custom_headers: headers that will be added to the request + :param bool raw: returns the direct response alongside the + deserialized response + :rtype: + :class:`AzureOperationPoller` + instance that returns :class:`Product + ` + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/lro/nonretryerror/put/201/creating/400/invalidjson' + + # Construct parameters + query_parameters = {} + + # Construct headers + header_parameters = {} + header_parameters['Content-Type'] = 'application/json; charset=utf-8' + if self.config.generate_client_request_id: + header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) + if custom_headers: + header_parameters.update(custom_headers) + if self.config.accept_language is not None: + header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') + + # Construct body + if product is not None: + body_content = self._serialize.body(product, 'Product') + else: + body_content = None + + # Construct and send request + def long_running_send(): + + request = self._client.put(url, query_parameters) + return self._client.send( + request, header_parameters, body_content, **operation_config) + + def get_long_running_status(status_link, headers={}): + + request = self._client.get(status_link) + request.headers.update(headers) + return self._client.send( + request, header_parameters, **operation_config) + + def get_long_running_output(response): + + if response.status_code not in [200, 201]: + exp = CloudError(response) + exp.request_id = response.headers.get('x-ms-request-id') + raise exp + + deserialized = None + + if response.status_code == 200: + deserialized = self._deserialize('Product', response) + if response.status_code == 201: + deserialized = self._deserialize('Product', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_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) + return AzureOperationPoller( + long_running_send, get_long_running_output, + get_long_running_status, long_running_operation_timeout) + def put_async_relative_retry400( self, product=None, custom_headers={}, raw=False, **operation_config): """ diff --git a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/operations/int_model.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/operations/int_model.py index 45d9ed146e..a2b06061ed 100644 --- a/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/operations/int_model.py +++ b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/BodyInteger/autorestintegertestservice/operations/int_model.py @@ -466,3 +466,178 @@ def put_min64( if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response + + def get_unix_time( + self, custom_headers={}, raw=False, **operation_config): + """ + Get datetime encoded as Unix time value + + :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: long + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/int/unixtime' + + # 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('long', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + + def put_unix_time_date( + self, int_body, custom_headers={}, raw=False, **operation_config): + """ + Put datetime encoded as Unix time + + :param int_body: + :type int_body: long + :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 = '/int/unixtime' + + # 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(int_body, 'long') + + # 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_invalid_unix_time( + self, custom_headers={}, raw=False, **operation_config): + """ + Get invalid Unix time value + + :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: long + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/int/invalidunixtime' + + # 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('long', response) + + if raw: + client_raw_response = ClientRawResponse(deserialized, response) + return client_raw_response + + return deserialized + + def get_null_unix_time( + self, custom_headers={}, raw=False, **operation_config): + """ + Get null Unix time value + + :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: long + :rtype: :class:`ClientRawResponse` + if raw=true + """ + # Construct URL + url = '/int/nullunixtime' + + # 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('long', 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/Url/autoresturltestservice/operations/paths.py b/AutoRest/Generators/Python/Python.Tests/Expected/AcceptanceTests/Url/autoresturltestservice/operations/paths.py index 97cd8878c0..c419d60782 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 @@ -1114,3 +1114,46 @@ def array_csv_in_path( if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response + + def unix_time_url( + self, unix_time_url_path, custom_headers={}, raw=False, **operation_config): + """ + Get the date 2016-04-13 encoded value as '1460505600' (Unix time) + + :param unix_time_url_path: Unix time encoded value + :type unix_time_url_path: long + :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/int/1460505600/{unixTimeUrlPath}' + path_format_arguments = { + 'unixTimeUrlPath': self._serialize.url("unix_time_url_path", unix_time_url_path, 'long') + } + 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 From f0dff3dcde4aa85705bc0b12d38d8981bfb17274 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Thu, 28 Apr 2016 12:48:43 -0700 Subject: [PATCH 05/13] Fixed fxcop warnings --- AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs b/AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs index dd0050ebae..a0c9b570f4 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs @@ -191,4 +191,6 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Scope = "member", Target = "Microsoft.Rest.Generator.NodeJS.TemplateModels.ClientModelExtensions.#ConstructMapper(Microsoft.Rest.Generator.ClientModel.IType,System.String,Microsoft.Rest.Generator.ClientModel.IParameter,System.Boolean,System.Boolean)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Scope = "member", Target = "Microsoft.Rest.Generator.NodeJS.NodeJsCodeNamer.#EscapeDefaultValue(System.String,Microsoft.Rest.Generator.ClientModel.IType)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "readOnly", Scope = "member", Target = "Microsoft.Rest.Generator.NodeJS.TemplateModels.ClientModelExtensions.#ConstructMapper(Microsoft.Rest.Generator.ClientModel.IType,System.String,Microsoft.Rest.Generator.ClientModel.IParameter,System.Boolean,System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Scope = "member", Target = "Microsoft.Rest.Generator.NodeJS.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(Microsoft.Rest.Generator.ClientModel.PrimaryType,Microsoft.Rest.Generator.Utilities.IScopeProvider,System.String,System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode", Scope = "member", Target = "Microsoft.Rest.Generator.NodeJS.TemplateModels.ClientModelExtensions.#ConstructMapper(Microsoft.Rest.Generator.ClientModel.IType,System.String,Microsoft.Rest.Generator.ClientModel.IParameter,System.Boolean,System.Boolean)")] From 5a032ae79273334be30794b4aef8a1e1bfd10d58 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Thu, 28 Apr 2016 13:38:18 -0700 Subject: [PATCH 06/13] remove null check validation for unixtime as they are treated as long in java --- .../java/fixtures/bodyinteger/IntOperations.java | 3 +-- .../java/fixtures/bodyinteger/IntOperationsImpl.java | 12 ++---------- .../src/main/java/fixtures/url/PathsOperations.java | 3 +-- .../main/java/fixtures/url/PathsOperationsImpl.java | 12 ++---------- .../Java/Java/TemplateModels/MethodTemplateModel.cs | 1 + 5 files changed, 7 insertions(+), 24 deletions(-) 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 06d2cb2eb7..9710c80eab 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 @@ -233,10 +233,9 @@ public interface IntOperations { * @param intBody the long 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 putUnixTimeDate(long intBody) throws ErrorException, IOException, IllegalArgumentException; + ServiceResponse putUnixTimeDate(long intBody) throws ErrorException, IOException; /** * Put datetime encoded as Unix time. 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 58cd455e4d..134ce02e57 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 @@ -620,13 +620,9 @@ private ServiceResponse getUnixTimeDelegate(Response respons * @param intBody the long 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 putUnixTimeDate(long intBody) throws ErrorException, IOException, IllegalArgumentException { - if (intBody == null) { - throw new IllegalArgumentException("Parameter intBody is required and cannot be null."); - } + public ServiceResponse putUnixTimeDate(long intBody) throws ErrorException, IOException { Call call = service.putUnixTimeDate(intBody); return putUnixTimeDateDelegate(call.execute()); } @@ -643,10 +639,6 @@ public ServiceCall putUnixTimeDateAsync(long intBody, final ServiceCallback call = service.putUnixTimeDate(intBody); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @@ -662,7 +654,7 @@ public void onResponse(Call call, Response response) return serviceCall; } - private ServiceResponse putUnixTimeDateDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + private ServiceResponse putUnixTimeDateDelegate(Response response) throws ErrorException, IOException { return new ServiceResponseBuilder(this.client.getMapperAdapter()) .register(200, new TypeToken() { }.getType()) .registerError(ErrorException.class) 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 6f82029407..1ccd08f952 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 @@ -508,10 +508,9 @@ public interface PathsOperations { * @param unixTimeUrlPath Unix time 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 unixTimeUrl(long unixTimeUrlPath) throws ErrorException, IOException, IllegalArgumentException; + ServiceResponse unixTimeUrl(long unixTimeUrlPath) throws ErrorException, IOException; /** * Get the date 2016-04-13 encoded value as '1460505600' (Unix time). 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 60f4ea1452..31942e3ce2 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 @@ -1428,13 +1428,9 @@ private ServiceResponse arrayCsvInPathDelegate(Response resp * @param unixTimeUrlPath Unix time 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 unixTimeUrl(long unixTimeUrlPath) throws ErrorException, IOException, IllegalArgumentException { - if (unixTimeUrlPath == null) { - throw new IllegalArgumentException("Parameter unixTimeUrlPath is required and cannot be null."); - } + public ServiceResponse unixTimeUrl(long unixTimeUrlPath) throws ErrorException, IOException { Call call = service.unixTimeUrl(unixTimeUrlPath); return unixTimeUrlDelegate(call.execute()); } @@ -1451,10 +1447,6 @@ public ServiceCall unixTimeUrlAsync(long unixTimeUrlPath, final ServiceCallback< if (serviceCallback == null) { throw new IllegalArgumentException("ServiceCallback is required for async calls."); } - if (unixTimeUrlPath == null) { - serviceCallback.failure(new IllegalArgumentException("Parameter unixTimeUrlPath is required and cannot be null.")); - return null; - } Call call = service.unixTimeUrl(unixTimeUrlPath); final ServiceCall serviceCall = new ServiceCall(call); call.enqueue(new ServiceResponseCallback(serviceCallback) { @@ -1470,7 +1462,7 @@ public void onResponse(Call call, Response response) return serviceCall; } - private ServiceResponse unixTimeUrlDelegate(Response response) throws ErrorException, IOException, IllegalArgumentException { + private ServiceResponse unixTimeUrlDelegate(Response response) throws ErrorException, IOException { return new ServiceResponseBuilder(this.client.getMapperAdapter()) .register(200, new TypeToken() { }.getType()) .registerError(ErrorException.class) diff --git a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs index c9f8bc6faf..7b9afbb821 100644 --- a/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs +++ b/AutoRest/Generators/Java/Java/TemplateModels/MethodTemplateModel.cs @@ -363,6 +363,7 @@ public IEnumerable RequiredNullableParameters !param.Type.IsPrimaryType(KnownPrimaryType.Double) && !param.Type.IsPrimaryType(KnownPrimaryType.Boolean) && !param.Type.IsPrimaryType(KnownPrimaryType.Long) && + !param.Type.IsPrimaryType(KnownPrimaryType.UnixTime) && !param.IsConstant && param.IsRequired) { yield return param; From 2f82af17924d40452618af256f909142a26de76f Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Thu, 28 Apr 2016 22:18:43 -0700 Subject: [PATCH 07/13] unixTime in node.js --- .../AcceptanceTests/acceptanceTests.ts | 30 +++++++++++++++++ .../BodyInteger/operations/index.d.ts | 18 +++++------ .../BodyInteger/operations/intModel.js | 23 ++++++------- .../operations/index.d.ts | 18 +++++------ .../operations/intModel.js | 23 ++++++------- .../AcceptanceTests/Url/operations/index.d.ts | 6 ++-- .../AcceptanceTests/Url/operations/paths.js | 11 ++++--- .../NodeJS/NodeJS/ClientModelExtensions.cs | 26 +++++++++++---- .../NodeJS/NodeJS/NodeJsCodeNamer.cs | 8 ++--- .../NodeJS/ms-rest/lib/serialization.js | 32 +++++++++++++++++-- 10 files changed, 134 insertions(+), 61 deletions(-) diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts index 0a81b34200..53e027b7e9 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts @@ -199,6 +199,29 @@ describe('nodejs', function () { }); }); }); + + it('should put and get UnixTime date correctly', function (done) { + var d = new Date(2016, 3, 12, 17, 0, 0); + testClient.intModel.putUnixTimeDate(d, function (error, result) { + should.not.exist(error); + testClient.intModel.getUnixTime(function (error, result) { + should.not.exist(error); + assert.deepEqual(result, d); + done(); + }); + }); + }); + + it('should throw an error for invalid UnixTime date anf get null value for UnixTime', function (done) { + testClient.intModel.getInvalidUnixTime(function (error, result) { + should.exist(error); + testClient.intModel.getNullUnixTime(function (error, result) { + should.not.exist(error); + should.not.exist(result); + done(); + }); + }); + }); }); describe('CompositeBoolInt Client', function () { @@ -1891,6 +1914,13 @@ describe('nodejs', function () { }); }); + it('should work when path has a paramaeter in UnixTime format', function (done) { + testClient.paths.unixTimeUrl(new Date(2016, 3, 12, 17, 0, 0), function (error, result) { + should.not.exist(error); + 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); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/index.d.ts index 1b00b43d81..6fddcb9d06 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/index.d.ts @@ -179,13 +179,13 @@ export interface IntModel { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - getUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; - getUnixTime(callback: ServiceCallback): void; + getUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getUnixTime(callback: ServiceCallback): void; /** * Put datetime encoded as Unix time * - * @param {number} intBody + * @param {date} intBody * * @param {object} [options] Optional Parameters. * @@ -195,8 +195,8 @@ export interface IntModel { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - putUnixTimeDate(intBody: number, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; - putUnixTimeDate(intBody: number, callback: ServiceCallback): void; + putUnixTimeDate(intBody: Date, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + putUnixTimeDate(intBody: Date, callback: ServiceCallback): void; /** * Get invalid Unix time value @@ -209,8 +209,8 @@ export interface IntModel { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - getInvalidUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; - getInvalidUnixTime(callback: ServiceCallback): void; + getInvalidUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getInvalidUnixTime(callback: ServiceCallback): void; /** * Get null Unix time value @@ -223,6 +223,6 @@ export interface IntModel { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - getNullUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; - getNullUnixTime(callback: ServiceCallback): void; + getNullUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getNullUnixTime(callback: ServiceCallback): void; } diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/intModel.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/intModel.js index b1ed3fbf47..290a93e9b3 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/intModel.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/BodyInteger/operations/intModel.js @@ -1210,7 +1210,7 @@ IntModel.prototype.putMin64 = function (intBody, options, callback) { * * {Error} err - The Error object if an error occurred, null otherwise. * - * {number} [result] - The deserialized result object. + * {date} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * @@ -1293,7 +1293,7 @@ IntModel.prototype.getUnixTime = function (options, callback) { required: false, serializedName: 'parsedResponse', type: { - name: 'Number' + name: 'UnixTime' } }; result = client.deserialize(resultMapper, parsedResponse, 'result'); @@ -1313,7 +1313,7 @@ IntModel.prototype.getUnixTime = function (options, callback) { /** * Put datetime encoded as Unix time * - * @param {number} intBody + * @param {date} intBody * * @param {object} [options] Optional Parameters. * @@ -1343,9 +1343,10 @@ IntModel.prototype.putUnixTimeDate = function (intBody, options, callback) { } // Validate try { - if (intBody === null || intBody === undefined || typeof intBody !== 'number') { - throw new Error('intBody cannot be null or undefined and it must be of type number.'); - } + if(!intBody || !(intBody instanceof Date || + (typeof intBody.valueOf() === 'string' && !isNaN(Date.parse(intBody))))) { + throw new Error('intBody cannot be null or undefined and it must be of type date.'); + } } catch (error) { return callback(error); } @@ -1380,7 +1381,7 @@ IntModel.prototype.putUnixTimeDate = function (intBody, options, callback) { required: true, serializedName: 'intBody', type: { - name: 'Number' + name: 'UnixTime' } }; requestModel = client.serialize(requestModelMapper, intBody, 'intBody'); @@ -1445,7 +1446,7 @@ IntModel.prototype.putUnixTimeDate = function (intBody, options, callback) { * * {Error} err - The Error object if an error occurred, null otherwise. * - * {number} [result] - The deserialized result object. + * {date} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * @@ -1528,7 +1529,7 @@ IntModel.prototype.getInvalidUnixTime = function (options, callback) { required: false, serializedName: 'parsedResponse', type: { - name: 'Number' + name: 'UnixTime' } }; result = client.deserialize(resultMapper, parsedResponse, 'result'); @@ -1559,7 +1560,7 @@ IntModel.prototype.getInvalidUnixTime = function (options, callback) { * * {Error} err - The Error object if an error occurred, null otherwise. * - * {number} [result] - The deserialized result object. + * {date} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * @@ -1642,7 +1643,7 @@ IntModel.prototype.getNullUnixTime = function (options, callback) { required: false, serializedName: 'parsedResponse', type: { - name: 'Number' + name: 'UnixTime' } }; result = client.deserialize(resultMapper, parsedResponse, 'result'); diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/index.d.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/index.d.ts index ac60442293..507488a58f 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/index.d.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/index.d.ts @@ -276,13 +276,13 @@ export interface IntModel { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - getUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; - getUnixTime(callback: ServiceCallback): void; + getUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getUnixTime(callback: ServiceCallback): void; /** * Put datetime encoded as Unix time * - * @param {number} intBody + * @param {date} intBody * * @param {object} [options] Optional Parameters. * @@ -292,8 +292,8 @@ export interface IntModel { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - putUnixTimeDate(intBody: number, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; - putUnixTimeDate(intBody: number, callback: ServiceCallback): void; + putUnixTimeDate(intBody: Date, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + putUnixTimeDate(intBody: Date, callback: ServiceCallback): void; /** * Get invalid Unix time value @@ -306,8 +306,8 @@ export interface IntModel { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - getInvalidUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; - getInvalidUnixTime(callback: ServiceCallback): void; + getInvalidUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getInvalidUnixTime(callback: ServiceCallback): void; /** * Get null Unix time value @@ -320,6 +320,6 @@ export interface IntModel { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - getNullUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; - getNullUnixTime(callback: ServiceCallback): void; + getNullUnixTime(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + getNullUnixTime(callback: ServiceCallback): void; } diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/intModel.js b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/intModel.js index 42f1d72ab3..d00f8cb625 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/intModel.js +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/Expected/AcceptanceTests/CompositeBoolIntClient/operations/intModel.js @@ -1210,7 +1210,7 @@ IntModel.prototype.putMin64 = function (intBody, options, callback) { * * {Error} err - The Error object if an error occurred, null otherwise. * - * {number} [result] - The deserialized result object. + * {date} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * @@ -1293,7 +1293,7 @@ IntModel.prototype.getUnixTime = function (options, callback) { required: false, serializedName: 'parsedResponse', type: { - name: 'Number' + name: 'UnixTime' } }; result = client.deserialize(resultMapper, parsedResponse, 'result'); @@ -1313,7 +1313,7 @@ IntModel.prototype.getUnixTime = function (options, callback) { /** * Put datetime encoded as Unix time * - * @param {number} intBody + * @param {date} intBody * * @param {object} [options] Optional Parameters. * @@ -1343,9 +1343,10 @@ IntModel.prototype.putUnixTimeDate = function (intBody, options, callback) { } // Validate try { - if (intBody === null || intBody === undefined || typeof intBody !== 'number') { - throw new Error('intBody cannot be null or undefined and it must be of type number.'); - } + if(!intBody || !(intBody instanceof Date || + (typeof intBody.valueOf() === 'string' && !isNaN(Date.parse(intBody))))) { + throw new Error('intBody cannot be null or undefined and it must be of type date.'); + } } catch (error) { return callback(error); } @@ -1380,7 +1381,7 @@ IntModel.prototype.putUnixTimeDate = function (intBody, options, callback) { required: true, serializedName: 'intBody', type: { - name: 'Number' + name: 'UnixTime' } }; requestModel = client.serialize(requestModelMapper, intBody, 'intBody'); @@ -1445,7 +1446,7 @@ IntModel.prototype.putUnixTimeDate = function (intBody, options, callback) { * * {Error} err - The Error object if an error occurred, null otherwise. * - * {number} [result] - The deserialized result object. + * {date} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * @@ -1528,7 +1529,7 @@ IntModel.prototype.getInvalidUnixTime = function (options, callback) { required: false, serializedName: 'parsedResponse', type: { - name: 'Number' + name: 'UnixTime' } }; result = client.deserialize(resultMapper, parsedResponse, 'result'); @@ -1559,7 +1560,7 @@ IntModel.prototype.getInvalidUnixTime = function (options, callback) { * * {Error} err - The Error object if an error occurred, null otherwise. * - * {number} [result] - The deserialized result object. + * {date} [result] - The deserialized result object. * * {object} [request] - The HTTP Request object if an error did not occur. * @@ -1642,7 +1643,7 @@ IntModel.prototype.getNullUnixTime = function (options, callback) { required: false, serializedName: 'parsedResponse', type: { - name: 'Number' + name: 'UnixTime' } }; result = client.deserialize(resultMapper, parsedResponse, 'result'); 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 3f5e246438..36fd5ba34f 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 @@ -398,7 +398,7 @@ export interface Paths { /** * Get the date 2016-04-13 encoded value as '1460505600' (Unix time) * - * @param {number} unixTimeUrlPath Unix time encoded value + * @param {date} unixTimeUrlPath Unix time encoded value * * @param {object} [options] Optional Parameters. * @@ -408,8 +408,8 @@ export interface Paths { * @param {ServiceCallback} [callback] callback function; see ServiceCallback * doc in ms-rest index.d.ts for details */ - unixTimeUrl(unixTimeUrlPath: number, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; - unixTimeUrl(unixTimeUrlPath: number, callback: ServiceCallback): void; + unixTimeUrl(unixTimeUrlPath: Date, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback): void; + unixTimeUrl(unixTimeUrlPath: Date, 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 4039b0ce96..2b5ff16d6b 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 @@ -2461,7 +2461,7 @@ Paths.prototype.arrayCsvInPath = function (arrayPath, options, callback) { /** * Get the date 2016-04-13 encoded value as '1460505600' (Unix time) * - * @param {number} unixTimeUrlPath Unix time encoded value + * @param {date} unixTimeUrlPath Unix time encoded value * * @param {object} [options] Optional Parameters. * @@ -2491,9 +2491,10 @@ Paths.prototype.unixTimeUrl = function (unixTimeUrlPath, options, callback) { } // Validate try { - if (unixTimeUrlPath === null || unixTimeUrlPath === undefined || typeof unixTimeUrlPath !== 'number') { - throw new Error('unixTimeUrlPath cannot be null or undefined and it must be of type number.'); - } + if(!unixTimeUrlPath || !(unixTimeUrlPath instanceof Date || + (typeof unixTimeUrlPath.valueOf() === 'string' && !isNaN(Date.parse(unixTimeUrlPath))))) { + throw new Error('unixTimeUrlPath cannot be null or undefined and it must be of type date.'); + } } catch (error) { return callback(error); } @@ -2501,7 +2502,7 @@ Paths.prototype.unixTimeUrl = function (unixTimeUrlPath, options, callback) { // Construct URL var requestUrl = this.client.baseUri + '//paths/int/1460505600/{unixTimeUrlPath}'; - requestUrl = requestUrl.replace('{unixTimeUrlPath}', encodeURIComponent(unixTimeUrlPath.toString())); + requestUrl = requestUrl.replace('{unixTimeUrlPath}', encodeURIComponent(client.serialize({required: true, serializedName: 'unixTimeUrlPath', type: {name: 'UnixTime'}}, unixTimeUrlPath, 'unixTimeUrlPath'))); // trim all duplicate forward slashes in the url var regex = /([^:]\/)\/+/gi; requestUrl = requestUrl.replace(regex, '$1'); diff --git a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs index 8f36adeec8..ba3a24c17b 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/ClientModelExtensions.cs @@ -131,6 +131,12 @@ public static string ToString(this IType type, string reference) return string.Format(CultureInfo.InvariantCulture, "client.serialize({{required: true, serializedName: '{0}', type: {{name: 'Base64Url'}}}}, {0}, '{0}')", reference); } + + if (known.Type == KnownPrimaryType.UnixTime) + { + return string.Format(CultureInfo.InvariantCulture, + "client.serialize({{required: true, serializedName: '{0}', type: {{name: 'UnixTime'}}}}, {0}, '{0}')", reference); + } } return string.Format(CultureInfo.InvariantCulture, "{0}.toString()", reference); @@ -195,8 +201,7 @@ private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvid primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || - primary.Type == KnownPrimaryType.Object || - primary.Type == KnownPrimaryType.UnixTime) + primary.Type == KnownPrimaryType.Object) { if (isRequired) { @@ -254,7 +259,8 @@ private static string ValidatePrimaryType(this PrimaryType primary, IScopeProvid builder.AppendLine("if ({0} && !Buffer.isBuffer({0})) {{", valueReference, lowercaseTypeName); return ConstructValidationCheck(builder, typeErrorMessage, valueReference, primary.Name).ToString(); } - else if (primary.Type == KnownPrimaryType.DateTime || primary.Type == KnownPrimaryType.Date || primary.Type == KnownPrimaryType.DateTimeRfc1123) + else if (primary.Type == KnownPrimaryType.DateTime || primary.Type == KnownPrimaryType.Date || + primary.Type == KnownPrimaryType.DateTimeRfc1123 || primary.Type == KnownPrimaryType.UnixTime) { if (isRequired) { @@ -303,11 +309,13 @@ private static string PrimaryTSType(this PrimaryType primary) if (primary.Type == KnownPrimaryType.Boolean) return "boolean"; - else if (primary.Type == KnownPrimaryType.Double || primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || primary.Type == KnownPrimaryType.UnixTime) + else if (primary.Type == KnownPrimaryType.Double || primary.Type == KnownPrimaryType.Decimal || + primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long) return "number"; else if (primary.Type == KnownPrimaryType.String || primary.Type == KnownPrimaryType.Uuid) return "string"; - else if (primary.Type == KnownPrimaryType.Date || primary.Type == KnownPrimaryType.DateTime || primary.Type == KnownPrimaryType.DateTimeRfc1123) + else if (primary.Type == KnownPrimaryType.Date || primary.Type == KnownPrimaryType.DateTime || + primary.Type == KnownPrimaryType.DateTimeRfc1123 || primary.Type == KnownPrimaryType.UnixTime) return "Date"; else if (primary.Type == KnownPrimaryType.Object) return "any"; // TODO: test this @@ -747,8 +755,8 @@ public static string ConstructMapper(this IType type, string serializedName, IPa { builder.AppendLine("type: {").Indent().AppendLine("name: 'Boolean'").Outdent().AppendLine("}"); } - else if(primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || primary.Type == KnownPrimaryType.Decimal || - primary.Type == KnownPrimaryType.Double || primary.Type == KnownPrimaryType.UnixTime) + else if (primary.Type == KnownPrimaryType.Int || primary.Type == KnownPrimaryType.Long || + primary.Type == KnownPrimaryType.Decimal || primary.Type == KnownPrimaryType.Double) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Number'").Outdent().AppendLine("}"); } @@ -784,6 +792,10 @@ public static string ConstructMapper(this IType type, string serializedName, IPa { builder.AppendLine("type: {").Indent().AppendLine("name: 'TimeSpan'").Outdent().AppendLine("}"); } + else if (primary.Type == KnownPrimaryType.UnixTime) + { + builder.AppendLine("type: {").Indent().AppendLine("name: 'UnixTime'").Outdent().AppendLine("}"); + } else if (primary.Type == KnownPrimaryType.Object) { builder.AppendLine("type: {").Indent().AppendLine("name: 'Object'").Outdent().AppendLine("}"); diff --git a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs index d2f43a402f..2dc7c2f0ed 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/NodeJsCodeNamer.cs @@ -365,6 +365,10 @@ private static IType NormalizePrimaryType(PrimaryType primaryType) { primaryType.Name = "Date"; } + else if (primaryType.Type == KnownPrimaryType.UnixTime) + { + primaryType.Name = "Date"; + } else if (primaryType.Type == KnownPrimaryType.Double) { primaryType.Name = "Number"; @@ -393,10 +397,6 @@ 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/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js index de8d0778ef..f802dd4384 100644 --- a/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js +++ b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js @@ -74,7 +74,7 @@ exports.serialize = function (mapper, object, objectName) { payload = serializeBasicTypes.call(this, mapperType, objectName, object); } else if (mapperType.match(/^Enum$/ig) !== null) { payload = serializeEnumType.call(this, objectName, mapper.type.allowedValues, object); - } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123)$/ig) !== null) { + } else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/ig) !== null) { payload = serializeDateTypes.call(this, mapperType, object, objectName); } else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = serializeBufferType.call(this, objectName, object); @@ -370,6 +370,13 @@ function serializeDateTypes(typeName, value, objectName) { throw new Error(util.format('%s must be an instanceof Date or a string in RFC-1123 format.', objectName)); } value = (value instanceof Date) ? value.toUTCString() : new Date(value).toUTCString(); + } else if (typeName.match(/^UnixTime$/ig) !== null) { + if (!(value instanceof Date || + (typeof value.valueOf() === 'string' && !isNaN(Date.parse(value))))) { + throw new Error(util.format('%s must be an instanceof Date or a string in RFC-1123/ISO8601 format ' + + 'for it to be serialized in UnixTime/Epoch format.', objectName)); + } + value = dateToUnixTime(value); } else if (typeName.match(/^TimeSpan$/ig) !== null) { if (!moment.isDuration(value)) { throw new Error(util.format('%s must be a TimeSpan/Duration.', objectName)); @@ -402,8 +409,10 @@ exports.deserialize = function (mapper, responseBody, objectName) { payload = responseBody; } else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/ig) !== null) { payload = new Date(responseBody); - } else if (mapperType.match(/^(TimeSpan)$/ig) !== null) { + } else if (mapperType.match(/^TimeSpan$/ig) !== null) { payload = moment.duration(responseBody); + } else if (mapperType.match(/^UnixTime$/ig) !== null) { + payload = unixTimeToDate(responseBody); } else if (mapperType.match(/^ByteArray$/ig) !== null) { payload = new Buffer(responseBody, 'base64'); } else if (mapperType.match(/^Base64Url$/ig) !== null) { @@ -595,4 +604,23 @@ function base64UrlToBuffer(str) { return new Buffer(str, 'base64'); } +function dateToUnixTime(d) { + if (!d) { + return null; + } + // A Date can be converted to string in JSON-clone operations, so let's tolerate. + if (typeof d.valueOf() === 'string') { + d = new Date(d); + } + var foo = parseInt(d.getTime() / 1000); + return foo; +} + +function unixTimeToDate(n) { + if (!n) { + return null; + } + return new Date(n*1000); +} + exports = module.exports; \ No newline at end of file From 54cfaac98f0c4a3b41f3e7ab856aa6d2cfbce6e4 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Thu, 28 Apr 2016 22:23:27 -0700 Subject: [PATCH 08/13] modification --- ClientRuntimes/NodeJS/ms-rest/lib/serialization.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js index f802dd4384..d71e1ab54a 100644 --- a/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js +++ b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js @@ -612,8 +612,7 @@ function dateToUnixTime(d) { if (typeof d.valueOf() === 'string') { d = new Date(d); } - var foo = parseInt(d.getTime() / 1000); - return foo; + return parseInt(d.getTime() / 1000); } function unixTimeToDate(n) { From 63fee4f2752daef93d42ce1778d2d886c75e9b66 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Fri, 29 Apr 2016 14:00:49 -0700 Subject: [PATCH 09/13] UnixTime tests --- .../NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts | 4 ++-- ClientRuntimes/NodeJS/ms-rest/README.md | 3 ++- ClientRuntimes/NodeJS/ms-rest/lib/serialization.js | 1 - ClientRuntimes/NodeJS/ms-rest/test/serializationTests.js | 6 ++++++ 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts index 53e027b7e9..db5042f716 100644 --- a/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts +++ b/AutoRest/Generators/NodeJS/NodeJS.Tests/AcceptanceTests/acceptanceTests.ts @@ -201,7 +201,7 @@ describe('nodejs', function () { }); it('should put and get UnixTime date correctly', function (done) { - var d = new Date(2016, 3, 12, 17, 0, 0); + var d = new Date('2016-04-13T00:00:00.000Z'); testClient.intModel.putUnixTimeDate(d, function (error, result) { should.not.exist(error); testClient.intModel.getUnixTime(function (error, result) { @@ -1915,7 +1915,7 @@ describe('nodejs', function () { }); it('should work when path has a paramaeter in UnixTime format', function (done) { - testClient.paths.unixTimeUrl(new Date(2016, 3, 12, 17, 0, 0), function (error, result) { + testClient.paths.unixTimeUrl(new Date('2016-04-13T00:00:00.000Z'), function (error, result) { should.not.exist(error); done(); }); diff --git a/ClientRuntimes/NodeJS/ms-rest/README.md b/ClientRuntimes/NodeJS/ms-rest/README.md index cb4aca73ab..1da52bff1a 100644 --- a/ClientRuntimes/NodeJS/ms-rest/README.md +++ b/ClientRuntimes/NodeJS/ms-rest/README.md @@ -18,7 +18,7 @@ var msrest = require('ms-rest'); ## Serialization/Deserialization Features - Type checking - - (String, Number, Boolean, ByteArray, Date, DateTime, Enum, TimeSpan, DateTimeRfc1123, Object, Stream, Sequence, Dictionary, Composite, Uuid(as a string)) + - (String, Number, Boolean, ByteArray, Base64Url, Date, DateTime, Enum, TimeSpan, DateTimeRfc1123, UnixTime, Object, Stream, Sequence, Dictionary, Composite, Uuid(as a string)) - Validation of specified constraints - ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems - Flattening/Unflattening properties @@ -26,6 +26,7 @@ Features - Model Properties marked as constant are set during serialization, irrespective of they being provided or not - Required check (If a model or property is marked required and is not provided in the object then an error is thrown) - Readonly check (If a model or property is marked readonly then it is not sent on the wire during, serialization) +- Serializing Constant values - serialize an array of dictionary of primitive values ```javascript diff --git a/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js index d71e1ab54a..671292b9f4 100644 --- a/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js +++ b/ClientRuntimes/NodeJS/ms-rest/lib/serialization.js @@ -608,7 +608,6 @@ function dateToUnixTime(d) { if (!d) { return null; } - // A Date can be converted to string in JSON-clone operations, so let's tolerate. if (typeof d.valueOf() === 'string') { d = new Date(d); } diff --git a/ClientRuntimes/NodeJS/ms-rest/test/serializationTests.js b/ClientRuntimes/NodeJS/ms-rest/test/serializationTests.js index d9be4bd39f..32c89671d3 100644 --- a/ClientRuntimes/NodeJS/ms-rest/test/serializationTests.js +++ b/ClientRuntimes/NodeJS/ms-rest/test/serializationTests.js @@ -195,6 +195,12 @@ describe('msrest', function () { serializedDateString.should.equal('+010000-01-01T11:59:59.000Z'); done(); }); + it('should correctly serialize a Date object with max value and format UnixTime', function (done) { + mapper = { type : { name: 'UnixTime' } }; + var serializedDate = msRest.serialize(mapper, new Date('9999-12-31T23:59:59-12:00'), 'dateTimeObj'); + serializedDate.should.equal(253402343999); + done(); + }); it('should correctly serialize a string in DateTimeRfc1123', function (done) { mapper = { type : { name: 'DateTimeRfc1123' } }; var rfc = new Date('Mon, 01 Jan 0001 00:00:00 GMT'); From 5e85f673eb71c37159748fdbac16a92f6435d5fd Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Fri, 29 Apr 2016 16:35:21 -0700 Subject: [PATCH 10/13] FxCop warnings --- AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs | 1 + 1 file changed, 1 insertion(+) diff --git a/AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs b/AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs index a0c9b570f4..9fecaab118 100644 --- a/AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs +++ b/AutoRest/Generators/NodeJS/NodeJS/GlobalSuppressions.cs @@ -193,4 +193,5 @@ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "readOnly", Scope = "member", Target = "Microsoft.Rest.Generator.NodeJS.TemplateModels.ClientModelExtensions.#ConstructMapper(Microsoft.Rest.Generator.ClientModel.IType,System.String,Microsoft.Rest.Generator.ClientModel.IParameter,System.Boolean,System.Boolean)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Scope = "member", Target = "Microsoft.Rest.Generator.NodeJS.TemplateModels.ClientModelExtensions.#ValidatePrimaryType(Microsoft.Rest.Generator.ClientModel.PrimaryType,Microsoft.Rest.Generator.Utilities.IScopeProvider,System.String,System.Boolean)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA1505:AvoidUnmaintainableCode", Scope = "member", Target = "Microsoft.Rest.Generator.NodeJS.TemplateModels.ClientModelExtensions.#ConstructMapper(Microsoft.Rest.Generator.ClientModel.IType,System.String,Microsoft.Rest.Generator.ClientModel.IParameter,System.Boolean,System.Boolean)")] +[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "UnixTime", Scope = "member", Target = "Microsoft.Rest.Generator.NodeJS.TemplateModels.ClientModelExtensions.#ConstructMapper(Microsoft.Rest.Generator.ClientModel.IType,System.String,Microsoft.Rest.Generator.ClientModel.IParameter,System.Boolean,System.Boolean)")] From 55af5bef12e7924ec900e423a337bb54d91da8b8 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Mon, 2 May 2016 20:25:35 -0700 Subject: [PATCH 11/13] Redesigned the structure of AzureEnvironment and updated the environments with more values. --- .../ms-rest-azure/lib/azureEnvironment.js | 176 ++++++++++--- .../applicationTokenCredentials.js | 4 +- .../lib/credentials/userTokenCredentials.js | 4 +- .../NodeJS/ms-rest-azure/lib/index.d.ts | 234 ++++++++++++------ .../test/azureEnvironmentTests.js | 91 +++++++ .../NodeJS/ms-rest-azure/test/testlist.txt | 3 +- 6 files changed, 399 insertions(+), 113 deletions(-) create mode 100644 ClientRuntimes/NodeJS/ms-rest-azure/test/azureEnvironmentTests.js diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/lib/azureEnvironment.js b/ClientRuntimes/NodeJS/ms-rest-azure/lib/azureEnvironment.js index 9aa5e6fb2a..e902c471c5 100644 --- a/ClientRuntimes/NodeJS/ms-rest-azure/lib/azureEnvironment.js +++ b/ClientRuntimes/NodeJS/ms-rest-azure/lib/azureEnvironment.js @@ -2,48 +2,158 @@ // Licensed under the MIT License. See License.txt in the project root for license information. 'use strict'; - -var _ = require('underscore'); - +var util = require('util'); /** * @class * Initializes a new instance of the AzureEnvironment class. * @constructor - * @param {string} authenticationEndpoint - ActiveDirectory Endpoint for the Azure Environment. - * @param {string} tokenAudience - Token audience for an endpoint. - * @param {bool} [validateAuthority] - Determines whether the authentication endpoint should + * @param {string} parameters.name - The Environment name + * @param {string} parameters.portalUrl - the management portal URL + * @param {string} parameters.managementEndpointUrl - the management service endpoint + * @param {string} parameters.resourceManagerEndpointUrl - the resource management endpoint + * @param {string} parameters.activeDirectoryEndpointUrl - the Active Directory login endpoint + * @param {string} parameters.activeDirectoryResourceId - The resource ID to obtain AD tokens for + * @param {string} [parameters.publishingProfileUrl] - the publish settings file URL + * @param {string} [parameters.sqlManagementEndpointUrl] - the sql server management endpoint for mobile commands + * @param {string} [parameters.sqlServerHostnameSuffix] - the dns suffix for sql servers + * @param {string} [parameters.galleryEndpointUrl] - the template gallery endpoint + * @param {string} [parameters.activeDirectoryGraphResourceId] - the Active Directory resource ID + * @param {string} [parameters.activeDirectoryGraphApiVersion] - the Active Directory api version + * @param {string} [parameters.storageEndpointSuffix] - the endpoint suffix for storage accounts + * @param {string} [parameters.keyVaultDnsSuffix] - the keyvault service dns suffix + * @param {string} [parameters.azureDataLakeStoreFileSystemEndpointSuffix] - the data lake store filesystem service dns suffix + * @param {string} [parameters.azureDataLakeAnalyticsCatalogAndJobEndpointSuffix] - the data lake analytics job and catalog service dns suffix + * @param {bool} [parameters.validateAuthority] - Determines whether the authentication endpoint should * be validated with Azure AD. Default value is true. */ -function AzureEnvironment(authenticationEndpoint, tokenAudience, validateAuthority) { - this.authenticationEndpoint = authenticationEndpoint; - this.tokenAudience = tokenAudience; - this.validateAuthority = validateAuthority; -} +function AzureEnvironment(parameters) { + //Set defaults. + this.validateAuthority = true; -/** - * Provides the settings for authentication with Azure - */ -var Azure = new AzureEnvironment('https://login.microsoftonline.com/', - 'https://management.core.windows.net/', - true); + if (parameters) { + //Validate required parameters + var requiredParams = [ 'name', 'portalUrl', 'managementEndpointUrl', 'resourceManagerEndpointUrl', + 'activeDirectoryEndpointUrl', 'activeDirectoryResourceId']; + requiredParams.forEach(function (param) { + if (!parameters[param] || typeof parameters[param].valueOf() !== 'string') { + throw new Error(util.format('Please provide "%s" for the environment and it must be of type "string".', param)); + } + }); + //Assign provided parameters + for (var prop in parameters) { + this[prop] = parameters[prop]; + } + } +} +var supportedEnvironments = { + Azure: { + name: 'Azure', + portalUrl: 'http://go.microsoft.com/fwlink/?LinkId=254433', + publishingProfileUrl: 'http://go.microsoft.com/fwlink/?LinkId=254432', + managementEndpointUrl: 'https://management.core.windows.net', + resourceManagerEndpointUrl: 'https://management.azure.com/', + sqlManagementEndpointUrl: 'https://management.core.windows.net:8443/', + sqlServerHostnameSuffix: '.database.windows.net', + galleryEndpointUrl: 'https://gallery.azure.com/', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.com', + activeDirectoryResourceId: 'https://management.core.windows.net/', + activeDirectoryGraphResourceId: 'https://graph.windows.net/', + activeDirectoryGraphApiVersion: '2013-04-05', + storageEndpointSuffix: '.core.windows.net', + keyVaultDnsSuffix: '.vault.azure.net', + azureDataLakeStoreFileSystemEndpointSuffix: 'azuredatalakestore.net', + azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: 'azuredatalakeanalytics.net' + }, + AzureChina: { + name: 'AzureChina', + portalUrl: 'http://go.microsoft.com/fwlink/?LinkId=301902', + publishingProfileUrl: 'http://go.microsoft.com/fwlink/?LinkID=301774', + managementEndpointUrl: 'https://management.core.chinacloudapi.cn', + resourceManagerEndpointUrl: 'https://management.chinacloudapi.cn', + sqlManagementEndpointUrl: 'https://management.core.chinacloudapi.cn:8443/', + sqlServerHostnameSuffix: '.database.chinacloudapi.cn', + galleryEndpointUrl: 'https://gallery.chinacloudapi.cn/', + activeDirectoryEndpointUrl: 'https://login.chinacloudapi.cn', + activeDirectoryResourceId: 'https://management.core.chinacloudapi.cn/', + activeDirectoryGraphResourceId: 'https://graph.chinacloudapi.cn/', + activeDirectoryGraphApiVersion: '2013-04-05', + storageEndpointSuffix: '.core.chinacloudapi.cn', + keyVaultDnsSuffix: '.vault.azure.cn', + // TODO: add dns suffixes for the china cloud for datalake store and datalake analytics once they are defined. + azureDataLakeStoreFileSystemEndpointSuffix: 'N/A', + azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: 'N/A' + }, + AzureUSGovernment: { + name: 'AzureUSGovernment', + portalUrl: 'https://manage.windowsazure.us', + publishingProfileUrl: 'https://manage.windowsazure.us/publishsettings/index', + managementEndpointUrl: 'https://management.core.usgovcloudapi.net', + resourceManagerEndpointUrl: 'https://management.usgovcloudapi.net', + sqlManagementEndpointUrl: 'https://management.core.usgovcloudapi.net:8443/', + sqlServerHostnameSuffix: '.database.usgovcloudapi.net', + galleryEndpointUrl: 'https://gallery.usgovcloudapi.net/', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.com', + activeDirectoryResourceId: 'https://management.core.usgovcloudapi.net/', + activeDirectoryGraphResourceId: 'https://graph.windows.net/', + activeDirectoryGraphApiVersion: '2013-04-05', + storageEndpointSuffix: '.core.usgovcloudapi.net', + keyVaultDnsSuffix: '.vault.usgovcloudapi.net', + // TODO: add dns suffixes for the US government for datalake store and datalake analytics once they are defined. + azureDataLakeStoreFileSystemEndpointSuffix: 'N/A', + azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: 'N/A' + }, + AzureGermanCloud: { + name: 'AzureGermanCloud', + portalUrl: 'http://portal.microsoftazure.de/', + publishingProfileUrl: 'https://manage.microsoftazure.de/publishsettings/index', + managementEndpointUrl: 'https://management.core.cloudapi.de', + resourceManagerEndpointUrl: 'https://management.microsoftazure.de', + sqlManagementEndpointUrl: 'https://management.core.cloudapi.de:8443/', + sqlServerHostnameSuffix: '.database.cloudapi.de', + galleryEndpointUrl: 'https://gallery.cloudapi.de/', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.de', + activeDirectoryResourceId: 'https://management.core.cloudapi.de/', + activeDirectoryGraphResourceId: 'https://graph.cloudapi.de/', + activeDirectoryGraphApiVersion: '2013-04-05', + storageEndpointSuffix: '.core.cloudapi.de', + keyVaultDnsSuffix: '.vault.microsoftazure.de', + // TODO: add dns suffixes for the US government for datalake store and datalake analytics once they are defined. + azureDataLakeStoreFileSystemEndpointSuffix: 'N/A', + azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: 'N/A' + } +}; /** - * Provides the settings for authentication with Azure China + * Adds a new instance of the AzureEnvironment to the prototype. + * @param {string} parameters.name - The Environment name + * @param {string} parameters.portalUrl - the management portal URL + * @param {string} parameters.managementEndpointUrl - the management service endpoint + * @param {string} parameters.resourceManagerEndpointUrl - the resource management endpoint + * @param {string} parameters.activeDirectoryEndpointUrl - the Active Directory login endpoint + * @param {string} parameters.activeDirectoryResourceId - The resource ID to obtain AD tokens for + * @param {string} [parameters.publishingProfileUrl] - the publish settings file URL + * @param {string} [parameters.sqlManagementEndpointUrl] - the sql server management endpoint for mobile commands + * @param {string} [parameters.sqlServerHostnameSuffix] - the dns suffix for sql servers + * @param {string} [parameters.galleryEndpointUrl] - the template gallery endpoint + * @param {string} [parameters.activeDirectoryGraphResourceId] - the Active Directory resource ID + * @param {string} [parameters.activeDirectoryGraphApiVersion] - the Active Directory api version + * @param {string} [parameters.storageEndpointSuffix] - the endpoint suffix for storage accounts + * @param {string} [parameters.keyVaultDnsSuffix] - the keyvault service dns suffix + * @param {string} [parameters.azureDataLakeStoreFileSystemEndpointSuffix] - the data lake store filesystem service dns suffix + * @param {string} [parameters.azureDataLakeAnalyticsCatalogAndJobEndpointSuffix] - the data lake analytics job and catalog service dns suffix + * @param {bool} [parameters.validateAuthority] - Determines whether the authentication endpoint should + * be validated with Azure AD. Default value is true. + * @return {AzureEnvironment} - Reference to the newly added Environment */ -var AzureChina = new AzureEnvironment('https://login.chinacloudapi.cn/', - 'https://management.core.chinacloudapi.cn/', - true); +AzureEnvironment.prototype.add = function(parameters) { + var _environment = new AzureEnvironment(parameters); + AzureEnvironment.prototype[_environment.name] = _environment; + return _environment; +}; -/** - * Provides the settings for authentication with Azure US Government - */ -var AzureUSGovernment = new AzureEnvironment('https://login.microsoftonline.com/', - 'https://management.core.usgovcloudapi.net/', - true); +//Adding the supported environments +for(var key in supportedEnvironments) { + AzureEnvironment.prototype.add(supportedEnvironments[key]); +} -_.extend(module.exports, { - Azure: Azure, - AzureChina: AzureChina, - AzureEnvironment: AzureEnvironment, - AzureUSGovernment: AzureUSGovernment -}); +module.exports = new AzureEnvironment(); \ No newline at end of file diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/lib/credentials/applicationTokenCredentials.js b/ClientRuntimes/NodeJS/ms-rest-azure/lib/credentials/applicationTokenCredentials.js index 0c4fe85033..e096edbff2 100644 --- a/ClientRuntimes/NodeJS/ms-rest-azure/lib/credentials/applicationTokenCredentials.js +++ b/ClientRuntimes/NodeJS/ms-rest-azure/lib/credentials/applicationTokenCredentials.js @@ -65,10 +65,10 @@ function ApplicationTokenCredentials(clientId, domain, secret, options) { */ ApplicationTokenCredentials.prototype.signRequest = function (webResource, callback) { var self = this; - var authorityUrl = self.environment.authenticationEndpoint + self.domain; + var authorityUrl = self.environment.activeDirectoryEndpointUrl + self.domain; var context = new adal.AuthenticationContext(authorityUrl, self.environment.validateAuthority, self.tokenCache); - context.acquireTokenWithClientCredentials(self.environment.tokenAudience, self.clientId, self.secret, function (err, result) { + context.acquireTokenWithClientCredentials(self.environment.activeDirectoryResourceId, self.clientId, self.secret, function (err, result) { if (err) { return callback(new Error('Failed to acquire token for application. \n' + err)); } diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/lib/credentials/userTokenCredentials.js b/ClientRuntimes/NodeJS/ms-rest-azure/lib/credentials/userTokenCredentials.js index ea25138765..7b4f02cf72 100644 --- a/ClientRuntimes/NodeJS/ms-rest-azure/lib/credentials/userTokenCredentials.js +++ b/ClientRuntimes/NodeJS/ms-rest-azure/lib/credentials/userTokenCredentials.js @@ -78,10 +78,10 @@ function UserTokenCredentials(clientId, domain, username, password, clientRedire */ UserTokenCredentials.prototype.signRequest = function (webResource, callback) { var self = this; - var authorityUrl = self.environment.authenticationEndpoint + self.domain; + var authorityUrl = self.environment.activeDirectoryEndpointUrl + self.domain; var context = new adal.AuthenticationContext(authorityUrl, self.environment.validateAuthority, self.tokenCache); - context.acquireTokenWithUsernamePassword(self.environment.tokenAudience, self.username, self.password, self.clientId, function (err, result) { + context.acquireTokenWithUsernamePassword(self.environment.activeDirectoryResourceId, self.username, self.password, self.clientId, function (err, result) { if (err) { return callback(new Error('Failed to acquire token. \n' + err)); } diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/lib/index.d.ts b/ClientRuntimes/NodeJS/ms-rest-azure/lib/index.d.ts index 818d584985..ef4378cff4 100644 --- a/ClientRuntimes/NodeJS/ms-rest-azure/lib/index.d.ts +++ b/ClientRuntimes/NodeJS/ms-rest-azure/lib/index.d.ts @@ -1,22 +1,22 @@ import * as msRest from 'ms-rest'; export interface AzureServiceClientOptions extends msRest.ServiceClientOptions { - // TODO: Make this property have right type - // * @param {Array} [options.longRunningOperationRetryTimeout] - Retry timeout - longRunningOperationRetryTimeout?: any; + // TODO: Make this property have right type + // * @param {Array} [options.longRunningOperationRetryTimeout] - Retry timeout + longRunningOperationRetryTimeout?: any; } export class AzureServiceClient extends msRest.ServiceClient { - /** - * @class - * Initializes a new instance of the AzureServiceClient class. - * @constructor - * @param {ServiceClientCredentials} credentials - ApplicationTokenCredentials or - * UserTokenCredentials object used for authentication. - * - * @param {object} options - The parameter options used by ServiceClient - * - * @param {string} [options.acceptLanguage] - Gets or sets the preferred language for the response. + /** + * @class + * Initializes a new instance of the AzureServiceClient class. + * @constructor + * @param {ServiceClientCredentials} credentials - ApplicationTokenCredentials or + * UserTokenCredentials object used for authentication. + * + * @param {object} options - The parameter options used by ServiceClient + * + * @param {string} [options.acceptLanguage] - Gets or sets the preferred language for the response. * Default value is: 'en-US'. * * @param {boolean} [options.generateClientRequestId] - When set to true a unique x-ms-client-request-id value @@ -24,81 +24,165 @@ export class AzureServiceClient extends msRest.ServiceClient { * * @param {number} [options.longRunningOperationRetryTimeout] - Gets or sets the retry timeout in seconds for * Long Running Operations. Default value is 30. - */ - constructor(credentials: msRest.ServiceClientCredentials, options: AzureServiceClientOptions) + */ + constructor(credentials: msRest.ServiceClientCredentials, options: AzureServiceClientOptions) } export class AzureEnvironment { - /** - * Initializes a new instance of the AzureEnvironment class. - * @param {string} authenticationEndpoint - ActiveDirectory Endpoint for the Azure Environment. - * @param {string} tokenAudience - Token audience for an endpoint. - * @param {bool} [validateAuthority] - Determines whether the authentication endpoint should - * be validated with Azure AD. Default value is true. - */ - constructor(authenticationEndpoint: string, tokenAudience: string, validateAuthority: boolean); - - /** - * ActiveDirectory Endpoint for the Azure Environment - */ - authenticationEndpoint: string; - - /** - * Token audience for an endpoint. - */ - tokenAudience: string; - - /** - * Determines whether the authentication endpoint should be validated with Azure AD. Default value is true. - */ - validateAuthority: boolean; + /** + * Initializes a new instance of the AzureEnvironment class. + * @param {string} parameters.name - The Environment name + * @param {string} parameters.portalUrl - The management portal URL + * @param {string} parameters.managementEndpointUrl - The management service endpoint + * @param {string} parameters.resourceManagerEndpointUrl - The resource management endpoint + * @param {string} parameters.activeDirectoryEndpointUrl - The Active Directory login endpoint + * @param {string} parameters.activeDirectoryResourceId - The resource ID to obtain AD tokens for (token audience) + * @param {string} [parameters.publishingProfileUrl] - The publish settings file URL + * @param {string} [parameters.sqlManagementEndpointUrl] - The sql server management endpoint for mobile commands + * @param {string} [parameters.sqlServerHostnameSuffix] - The dns suffix for sql servers + * @param {string} [parameters.galleryEndpointUrl] - The template gallery endpoint + * @param {string} [parameters.activeDirectoryGraphResourceId] - The Active Directory resource ID + * @param {string} [parameters.activeDirectoryGraphApiVersion] - The Active Directory api version + * @param {string} [parameters.storageEndpointSuffix] - The endpoint suffix for storage accounts + * @param {string} [parameters.keyVaultDnsSuffix] - The keyvault service dns suffix + * @param {string} [parameters.azureDataLakeStoreFileSystemEndpointSuffix] - The data lake store filesystem service dns suffix + * @param {string} [parameters.azureDataLakeAnalyticsCatalogAndJobEndpointSuffix] - The data lake analytics job and catalog service dns suffix + * @param {bool} [parameters.validateAuthority] - Determines whether the authentication endpoint should + * be validated with Azure AD. Default value is true. + */ + constructor(parameters: any); + + /** + * The Environment name. + */ + name: string; + + /** + * The management portal URL. + */ + portalUrl: string; + + /** + * The management service endpoint. + */ + managementEndpointUrl: string; + + /** + * The resource management endpoint. + */ + resourceManagerEndpointUrl: string; + + /** + * The Active Directory login endpoint. + */ + activeDirectoryEndpointUrl: string; + + /** + * The resource ID to obtain AD tokens for (token audience). + */ + activeDirectoryResourceId: string; + + /** + * The publish settings file URL. + */ + publishingProfileUrl: string; + + /** + * The sql server management endpoint for mobile commands. + */ + sqlManagementEndpointUrl: string; + + /** + * The dns suffix for sql servers. + */ + sqlServerHostnameSuffix: string; + + /** + * The template gallery endpoint. + */ + galleryEndpointUrl: string; + + /** + * The Active Directory resource ID. + */ + activeDirectoryGraphResourceId: string; + + /** + * The Active Directory api version. + */ + activeDirectoryGraphApiVersion: string; + + /** + * The endpoint suffix for storage accounts. + */ + storageEndpointSuffix: string; + + /** + * The keyvault service dns suffix. + */ + keyVaultDnsSuffix: string; + + /** + * The data lake store filesystem service dns suffix. + */ + azureDataLakeStoreFileSystemEndpointSuffix: string; + + /** + * The data lake analytics job and catalog service dns suffix. + */ + azureDataLakeAnalyticsCatalogAndJobEndpointSuffix: string; + + /** + * Determines whether the authentication endpoint should be validated with Azure AD. Default value is true. + */ + validateAuthority: boolean; } export interface AzureTokenCredentialsOptions { - /** - * The Azure environment to authenticate with. - */ - environment?: AzureEnvironment; - - /** - * The authorization scheme. Default value is 'Bearer'. - */ - authorizationScheme?: string; - - // TODO: What type should this really have? How is it used? - /** - * The token cache. Default value is null. - */ - tokenCache?: any; + /** + * The Azure environment to authenticate with. + */ + environment?: AzureEnvironment; + + /** + * The authorization scheme. Default value is 'Bearer'. + */ + authorizationScheme?: string; + + // TODO: What type should this really have? How is it used? + /** + * The token cache. Default value is null. + */ + tokenCache?: any; } export class ApplicationTokenCredentials extends msRest.ServiceClientCredentials { - /** - * Creates a new ApplicationTokenCredentials object. - * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} - * for detailed instructions on creating an Azure Active Directory application. - * @param {string} clientId The active directory application client id. - * @param {string} domain The domain or tenant id containing this application. - * @param {string} secret The authentication secret for the application. - * @param {AzureTokenCredentialsOptions} options Object representing optional parameters. - */ - constructor(clientId: string, domain: string, secret: string, options?: AzureTokenCredentialsOptions); + /** + * Creates a new ApplicationTokenCredentials object. + * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} + * for detailed instructions on creating an Azure Active Directory application. + * @param {string} clientId The active directory application client id. + * @param {string} domain The domain or tenant id containing this application. + * @param {string} secret The authentication secret for the application. + * @param {AzureTokenCredentialsOptions} options Object representing optional parameters. + */ + constructor(clientId: string, domain: string, secret: string, options?: AzureTokenCredentialsOptions); } export class UserTokenCredentials extends msRest.ServiceClientCredentials { - /** - * Creates a new UserTokenCredentials object. - * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} - * for an example. - * @param {string} clientId The active directory application client id. - * @param {string} domain The domain or tenant id containing this application. - * @param {string} username The user name for the Organization Id account. - * @param {string} password The password for the Organization Id account. - * @param {string} clientRedirectUri The Uri where the user will be redirected after authenticating with AD. - * @param {AzureTokenCredentialsOptions} options Object representing optional parameters. - */ - constructor(clientId: string, domain: string, username: string, password: string, clientRedirectUri: string, options?: AzureTokenCredentialsOptions); + /** + * Creates a new UserTokenCredentials object. + * See {@link https://azure.microsoft.com/en-us/documentation/articles/active-directory-devquickstarts-dotnet/ Active Directory Quickstart for .Net} + * for an example. + * @param {string} clientId The active directory application client id. + * @param {string} domain The domain or tenant id containing this application. + * @param {string} username The user name for the Organization Id account. + * @param {string} password The password for the Organization Id account. + * @param {string} clientRedirectUri The Uri where the user will be redirected after authenticating with AD. + * @param {AzureTokenCredentialsOptions} options Object representing optional parameters. + */ + constructor(clientId: string, domain: string, username: string, password: string, clientRedirectUri: string, options?: AzureTokenCredentialsOptions); } // TODO: WHAT SHOULD WE EXPOSE HERE? diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/test/azureEnvironmentTests.js b/ClientRuntimes/NodeJS/ms-rest-azure/test/azureEnvironmentTests.js new file mode 100644 index 0000000000..01b6fbfd81 --- /dev/null +++ b/ClientRuntimes/NodeJS/ms-rest-azure/test/azureEnvironmentTests.js @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for license information. + +var should = require('should'); +var msRestAzure = require('../lib/msRestAzure'); + +describe('AzureEnvironment', function() { + it('can be properly required', function(done) { + var tempEnv = msRestAzure.AzureEnvironment; + tempEnv.validateAuthority.should.equal(true); + done(); + }); + + it('should show the details of Azure Production environment correctly', function(done) { + var tempEnv = msRestAzure.AzureEnvironment.Azure; + tempEnv.name.should.equal('Azure'); + tempEnv.activeDirectoryEndpointUrl.should.equal('https://login.microsoftonline.com'); + tempEnv.activeDirectoryResourceId.should.equal('https://management.core.windows.net/'); + tempEnv.managementEndpointUrl.should.equal('https://management.core.windows.net'); + tempEnv.resourceManagerEndpointUrl.should.equal('https://management.azure.com/'); + tempEnv.portalUrl.should.equal('http://go.microsoft.com/fwlink/?LinkId=254433'); + tempEnv.validateAuthority.should.equal(true); + done(); + }); + + it('should show the details of Azure China environment correctly', function(done) { + var tempEnv = msRestAzure.AzureEnvironment.AzureChina; + tempEnv.name.should.equal('AzureChina'); + tempEnv.activeDirectoryEndpointUrl.should.equal('https://login.chinacloudapi.cn'); + tempEnv.activeDirectoryResourceId.should.equal('https://management.core.chinacloudapi.cn/'); + tempEnv.managementEndpointUrl.should.equal('https://management.core.chinacloudapi.cn'); + tempEnv.resourceManagerEndpointUrl.should.equal('https://management.chinacloudapi.cn'); + tempEnv.portalUrl.should.equal('http://go.microsoft.com/fwlink/?LinkId=301902'); + tempEnv.validateAuthority.should.equal(true); + done(); + }); + + it('should show the details of Azure USGovernment environment correctly', function(done) { + var tempEnv = msRestAzure.AzureEnvironment.AzureUSGovernment; + tempEnv.name.should.equal('AzureUSGovernment'); + tempEnv.activeDirectoryEndpointUrl.should.equal('https://login.microsoftonline.com'); + tempEnv.activeDirectoryResourceId.should.equal('https://management.core.usgovcloudapi.net/'); + tempEnv.managementEndpointUrl.should.equal('https://management.core.usgovcloudapi.net'); + tempEnv.resourceManagerEndpointUrl.should.equal('https://management.usgovcloudapi.net'); + tempEnv.portalUrl.should.equal('https://manage.windowsazure.us'); + tempEnv.validateAuthority.should.equal(true); + done(); + }); + + it('should show the details of Azure GermanCloud environment correctly', function(done) { + var tempEnv = msRestAzure.AzureEnvironment.AzureGermanCloud; + tempEnv.name.should.equal('AzureGermanCloud'); + tempEnv.activeDirectoryEndpointUrl.should.equal('https://login.microsoftonline.de'); + tempEnv.activeDirectoryResourceId.should.equal('https://management.core.cloudapi.de/'); + tempEnv.managementEndpointUrl.should.equal('https://management.core.cloudapi.de'); + tempEnv.resourceManagerEndpointUrl.should.equal('https://management.microsoftazure.de'); + tempEnv.portalUrl.should.equal('http://portal.microsoftazure.de/'); + tempEnv.validateAuthority.should.equal(true); + done(); + }); + + it('should be able to add a new environment', function(done) { + var df = { + name: 'Dogfood', + portalUrl: 'http://go.microsoft.com/fwlink/?LinkId=254433', + managementEndpointUrl: 'https://management.core.windows.net', + resourceManagerEndpointUrl: 'https://management.azure.com/', + activeDirectoryEndpointUrl: 'https://login.microsoftonline.com', + activeDirectoryResourceId: 'https://management.core.windows.net/' + }; + var tempEnv = msRestAzure.AzureEnvironment; + var dfood = tempEnv.add(df); + dfood.name.should.equal('Dogfood'); + dfood.activeDirectoryEndpointUrl.should.equal('https://login.microsoftonline.com'); + dfood.activeDirectoryResourceId.should.equal('https://management.core.windows.net/'); + dfood.managementEndpointUrl.should.equal('https://management.core.windows.net'); + dfood.resourceManagerEndpointUrl.should.equal('https://management.azure.com/'); + dfood.portalUrl.should.equal('http://go.microsoft.com/fwlink/?LinkId=254433'); + dfood.validateAuthority.should.equal(true); + + //Verify that the environment properly got added to the prototype + tempEnv.Dogfood.name.should.equal('Dogfood'); + tempEnv.Dogfood.activeDirectoryEndpointUrl.should.equal('https://login.microsoftonline.com'); + tempEnv.Dogfood.activeDirectoryResourceId.should.equal('https://management.core.windows.net/'); + tempEnv.Dogfood.managementEndpointUrl.should.equal('https://management.core.windows.net'); + tempEnv.Dogfood.resourceManagerEndpointUrl.should.equal('https://management.azure.com/'); + tempEnv.Dogfood.portalUrl.should.equal('http://go.microsoft.com/fwlink/?LinkId=254433'); + tempEnv.Dogfood.validateAuthority.should.equal(true); + done(); + }); +}); \ No newline at end of file diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/test/testlist.txt b/ClientRuntimes/NodeJS/ms-rest-azure/test/testlist.txt index 6118755921..83a9769333 100644 --- a/ClientRuntimes/NodeJS/ms-rest-azure/test/testlist.txt +++ b/ClientRuntimes/NodeJS/ms-rest-azure/test/testlist.txt @@ -1 +1,2 @@ -azureServiceClientTests.js \ No newline at end of file +azureServiceClientTests.js +azureEnvironmentTests.js \ No newline at end of file From 88e367946e73545c92aa7d716ca97b4acfb10ec6 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Mon, 2 May 2016 20:31:22 -0700 Subject: [PATCH 12/13] getting rid of underscore.js as a dependency from ms-rest-azure --- ClientRuntimes/NodeJS/ms-rest-azure/package.json | 1 - ClientRuntimes/NodeJS/ms-rest-azure/test/package.json | 3 +-- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/package.json b/ClientRuntimes/NodeJS/ms-rest-azure/package.json index 0cb2731447..9ca0985902 100644 --- a/ClientRuntimes/NodeJS/ms-rest-azure/package.json +++ b/ClientRuntimes/NodeJS/ms-rest-azure/package.json @@ -24,7 +24,6 @@ "uuid": "2.0.1", "adal-node": "0.1.17", "ms-rest": "^1.12.0", - "underscore": "^1.4.0", "moment": "^2.6.0" }, "devDependencies": { diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/test/package.json b/ClientRuntimes/NodeJS/ms-rest-azure/test/package.json index a4970d007d..248a41a885 100644 --- a/ClientRuntimes/NodeJS/ms-rest-azure/test/package.json +++ b/ClientRuntimes/NodeJS/ms-rest-azure/test/package.json @@ -31,8 +31,7 @@ "xunit-file": "0.0.5", "mocha": "2.2.5", "should": "5.2.0", - "moment": "*", - "underscore": "*" + "moment": "*" }, "homepage": "https://github.com/Azure/AutoRest", "repository": { From 4f7dc492a4c1d707e7c47859c2c8ac9843280b31 Mon Sep 17 00:00:00 2001 From: Amar Zavery Date: Wed, 11 May 2016 12:17:11 -0700 Subject: [PATCH 13/13] updated node.js clientruntime version to 1.13.0 & 1.3.1 for ms-rest-azure and ms-rest resp. --- .../Azure.NodeJS/AzureNodeJSCodeGenerator.cs | 2 +- .../NodeJS/NodeJS/NodeJSCodeGenerator.cs | 2 +- ClientRuntimes/NodeJS/ms-rest-azure/LICENSE | 22 +++++++++++++++++++ .../NodeJS/ms-rest-azure/package.json | 13 ++++------- ClientRuntimes/NodeJS/ms-rest/LICENSE | 22 +++++++++++++++++++ ClientRuntimes/NodeJS/ms-rest/package.json | 11 +++------- 6 files changed, 53 insertions(+), 19 deletions(-) create mode 100644 ClientRuntimes/NodeJS/ms-rest-azure/LICENSE create mode 100644 ClientRuntimes/NodeJS/ms-rest/LICENSE diff --git a/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs b/AutoRest/Generators/NodeJS/Azure.NodeJS/AzureNodeJSCodeGenerator.cs index ac8eea6fb0..06bdbd8487 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.12.0"; + private const string ClientRuntimePackage = "ms-rest-azure version 1.13.0"; // List of models with paging extensions. private IList pageModels; diff --git a/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs b/AutoRest/Generators/NodeJS/NodeJS/NodeJSCodeGenerator.cs index 04bacdaeb5..2e59314d87 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.12.0"; + private const string ClientRuntimePackage = "ms-rest version 1.13.1"; public NodeJsCodeNamer Namer { get; private set; } diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/LICENSE b/ClientRuntimes/NodeJS/ms-rest-azure/LICENSE new file mode 100644 index 0000000000..b8b569d774 --- /dev/null +++ b/ClientRuntimes/NodeJS/ms-rest-azure/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/ClientRuntimes/NodeJS/ms-rest-azure/package.json b/ClientRuntimes/NodeJS/ms-rest-azure/package.json index 9ca0985902..1002e12f3e 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.12.0", + "version": "1.13.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" ], @@ -13,23 +13,18 @@ "engines": { "node": ">= 0.10.0" }, - "licenses": [ - { - "type": "MIT", - "url": "https://raw.githubusercontent.com/Microsoft/dotnet/master/LICENSE" - } - ], + "license": "MIT", "dependencies": { "async": "0.2.7", "uuid": "2.0.1", "adal-node": "0.1.17", - "ms-rest": "^1.12.0", + "ms-rest": "^1.13.1", "moment": "^2.6.0" }, "devDependencies": { "jshint": "2.6.3", "xunit-file": "0.0.5", - "mocha": "2.2.5", + "mocha": "2.4.5", "should": "5.2.0" }, "homepage": "https://github.com/Azure/AutoRest", diff --git a/ClientRuntimes/NodeJS/ms-rest/LICENSE b/ClientRuntimes/NodeJS/ms-rest/LICENSE new file mode 100644 index 0000000000..b8b569d774 --- /dev/null +++ b/ClientRuntimes/NodeJS/ms-rest/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Microsoft + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/ClientRuntimes/NodeJS/ms-rest/package.json b/ClientRuntimes/NodeJS/ms-rest/package.json index b21efcee2d..656299783e 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.12.0", + "version": "1.13.1", "description": "Client Runtime for Node.js client libraries generated using AutoRest", "tags": ["node", "microsoft", "autorest", "clientruntime"], "keywords": ["node", "microsoft", "autorest", "clientruntime"], @@ -14,12 +14,7 @@ "engines": { "node": ">= 0.10.0" }, - "licenses": [ - { - "type": "MIT", - "url": "https://raw.githubusercontent.com/Microsoft/dotnet/master/LICENSE" - } - ], + "license": "MIT", "dependencies": { "underscore": "^1.4.0", "tunnel": "~0.0.2", @@ -31,7 +26,7 @@ "devDependencies": { "jshint": "2.6.3", "xunit-file": "0.0.5", - "mocha": "2.2.5", + "mocha": "2.4.5", "should": "5.2.0", "node-uuid": "*" },